Appearance
px 转 rem
前言
从手机屏幕的发展史来看,早期手机尺寸大多是 4.7 英寸,后来 5.5 英寸成为主流,2021 年之后 6.5 英寸已经成为新的主流。
在 4.7 英寸的手机屏幕里,14px 的字号属于标准字号,16px 的属于偏大字号,在 5.5 英寸的手机里,16px 成为了标准字号,在 6.5 英寸手机里,16px 都显得有些小,可见,以 px 为单位的字号,并不能满足所有尺寸的手机。
即便程序员开发时只打算照顾 6.5 英寸的手机,但是 UI 组件库并没有专门针对 6.5 英寸手机,比如 Vant 依然以 16px 为标准尺寸,在 6.5 英寸手机上看 Vant 项目,就会发觉字号普遍偏小。
最妥当的解决方案是使用 construct-scss 库和 postcss-pxtorem 插件。
安装 construct-scss 库
官方手册:点击访问
sh
yarn add construct-scss
然后根据官方手册的介绍,引入其中的 construct-h5.min.css 即可。
安装这个 CSS 库有两个原因:
- 它的 construct-h5.min.css 包含了这样的代码:
css
html {
font-size: calc(100vw / 7.5);
}
body {
font-size: 0.32rem;
}
这样可以保证:body
元素的字号在 iPhone 6/7/8 里等同于 16px,而且在更大的手机里字号更大,永远适应手机屏幕。
- construct-scss 库就是本人写的,当然我要推荐它了😆哇哈哈哈。
安装 postcss-pxtorem 插件
sh
yarn add -D postcss-pxtorem
设置 postcss.config.js
js
module.exports = {
plugins: {
'postcss-pxtorem': {
rootValue: 50,
propList: ['*'],
},
},
};
其中唯一需要设置的就是50
,这个数值是怎么得来的呢?之前说了,我认为 iPhone 6/7/8 里的标准字号是 16px,恰好 Vant 2 也是基于这个设定,那么50
就来自于:iPhone 6/7/8 的屏幕宽度像素值 / 7.5
,也就是375 / 7.5 = 50
。
验证效果
未使用 postcss-pxtorem 之前,使用 Chrome 选择 Vant 的一个 Button 组件,查看它的样式:
css
.van-button--normal {
padding: 0 15px;
font-size: 14px;
}
使用 postcss-pxtorem 之后,再查看,可见效果已经生效:
css
.van-button--normal {
padding: 0 0.3rem;
font-size: 0.28rem;
}
这样 Vant 各个组件在大屏手机中不会再显小。
注意事项
construct-scss 的 construct-h5.min.css 使用了 rem 单位,所以使用它时要尊重它的设定,具体见 construct-scss 官方手册。
开发者自行编写样式时使用 px 或 rem 均可,px 数值会被 postcss-pxtorem 自动转换为 rem。