移动端适配
web | des |
---|---|
蓝湖 | 在线转换 |
PxCook | |
imgcook |
插件转换
postcss-pxtorem:px转换为rem
autoprefixer:自动管理css属性的浏览器前缀
sh
npm -i -D postcss autoprefixer postcss-pxtorem
创建postcss.config.js
js
module.exports = {
plugins: {
autoprefixer: {
overrideBrowserslist: ['Android >= 4.0', 'iOS >= 7'],
},
'postcss-pxtorem': {
// 根节点的 fontSize 值
rootValue: 16,
propList: ['*'],
selectorBlackList: [':root'],
},
},
}
获取用户屏幕宽度并设置HTML的fontsize
js
const rootValue = 16 // 设计稿的基准字体大小(通常是16px)
const rootWidth = 390 // 设计稿的基准宽度(这里是390px,可能是移动端设计稿宽度)
const deviceWidth = document.documentElement.clientWidth // 获取设备实际宽度
document.documentElement.style.fontSize = (deviceWidth * rootValue) / rootWidth + 'px'
工作原理
- rem单位:rem(root em)是相对于根元素(html)字体大小的单位。如果根字体大小是16px,那么1rem = 16px。
- 响应式原理:
- 设计稿宽度为390px时,根字体大小设置为16px
- 当设备宽度变化时,按比例调整根字体大小
- 公式:
当前根字体大小 = (设备宽度 × 设计稿根字体大小) / 设计稿宽度
- 实际应用:
- 在设计稿上测量一个元素宽度为195px(设计稿宽度的一半)
- 转换为rem:195px / 16px = 12.1875rem
- 在任何设备上,这个12.1875rem都会保持为当前视口宽度的一半