rem (root em) 属于相对单位, 其不是像 em 单位那样是相对于当前元素的字体大小 font-size 计算得出的值,rem 始终相对于页面根元素,即 html 的 font-size 大小计算得出。
所以我们可以使用 rem 作为页面布局主单位,再利用 媒体查询(@media screen) 或 javascript 动态计算并设置在不同屏幕大小下根元素 html 的 font-size 属性值,使得页面元素可以响应式的显示合适的大小。
动态设置 html 元素 font-size 的几种方式
配置固定媒体查询法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
| html,body{ margin: 0; }
@media screen and (min-width: 320px){ html{ font-size: 21.33px; } } @media screen and (min-width: 360px){ html{ font-size: 24px; } }
@media screen and (min-width: 375px){ html{ font-size: 25px; } } @media screen and (min-width: 384px){ html{ font-size: 25.6px; } }
@media screen and (min-width: 400px){ html{ font-size: 26.67px; } }
@media screen and (min-width: 414px){ html{ font-size: 27.6px; } } @media screen and (min-width: 424px){ html{ font-size: 28.27px; } }
@media screen and (min-width: 480px){ html{ font-size: 32px; } }
@media screen and (min-width: 540px){ html{ font-size: 36px; } }
|
js动态计算
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
|
var html = document.querySelector("html"); var w = document.body.offsetWidth;
var htmlFontSize = w * 54 / 640;
html.style.fontSize = htmlFontSize + "px";
window.addEventListener( "resize", function(){ var w = document.body.offsetWidth;
var htmlFontSize = w * 54 / 640;
if( htmlFontSize > 54 ){ htmlFontSize = 54; }
html.style.fontSize = htmlFontSize + "px"; });
|
基于rem和vw的计算方式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| html { font-size: 16px; }
@media screen and (min-width: 375px) { html { font-size: calc(100% + 2 * (100vw - 375px) / 39); font-size: calc(16px + 2 * (100vw - 375px) / 39); } } @media screen and (min-width: 414px) { html { font-size: calc(112.5% + 4 * (100vw - 414px) / 586); font-size: calc(18px + 4 * (100vw - 414px) / 586); } } @media screen and (min-width: 600px) { html { font-size: calc(125% + 4 * (100vw - 600px) / 400); font-size: calc(20px + 4 * (100vw - 600px) / 400); } } @media screen and (min-width: 1000px) { html { font-size: calc(137.5% + 6 * (100vw - 1000px) / 1000); font-size: calc(22px + 6 * (100vw - 1000px) / 1000); } }
|
实际应用
配合 sass 在实际项目中使用
通常我们想要使用 rem 布局,那么就需要解决 px 转 rem 的问题。以便在使用时,直观,易于理解。
借助 sass 中的 @function 将 px 转换成 rem:
1 2 3 4 5
| @function px2rem($px){ @return $px / 16px * 1rem; }
|
上面代码表示,在当前页面的 html 元素的 font-size 值为:16px 时,将 $px 转换为 rem 单位值。
1 2 3 4 5
| .box { width: px2rem(200px); }
|
上面代码将被编译为:
1 2 3
| .box{ width : 12.5rem; }
|
在实际项目开发时,我们可以将 此功能函数封装在一个单独的 util.scss 文件中
1 2 3 4 5 6 7 8
|
$base-root-font-size: 16px;
@function px2rem($px){ @return $px / $base-root-font-size * 1rem; }
|
将动态处理 html 元素的 font-size 的样式文件单独全局引入。
然后在你的 某个页面 的样式文件中引入你的功能函数。
1 2 3 4 5 6 7 8 9
| @import '@/style/util.scss'
// 开始你的表演 ...
.foo { width: px2rem(200px); }
|
就像上面代码那样,你只需要像之前你使用 px 进行布局一样简单,只不过是需要 加上 px2rem()。