为什么进行适配?
同样大小的页面元素在在不同宽度的屏幕下,布局会错乱。 元素没有在可视范围内,或者元素没有撑满整个屏幕,有空白的区域。
常见的适配方案
- 不同端使用不同的代码,比如PC端一套、移动端一套。
- 使用同一套代码,使用媒体查询来控制CSS样式@media。
- 移动端屏幕适配:
- 第一种是使用rem对于body的字体进行适配。
- 第二种是使用vw和vh来按照屏幕高度进行缩放。
如何将px转成rem?
使用post-css,是一个css转换工具,安装插件,autoprefixer是自动添加浏览器前缀的插件:
npm i postcss autoprefixer postcss-pxtorem -D
在根目录下创建一个postcss.config.js文件
module.exports = {
plugins: {
autoprefixer: {
overrideBrowserslist: ['Android >= 4.0', 'ios >= 7']
},
'postcss-pxtorem': {
rootValue: 16,
propList: ['*'], //修改所有的css
selectorBlackList: [':root'] // 忽略:root定义的值 vant使用的是root
}
}
}
在main.js里面写入以下计算,根据屏幕尺寸,动态计算大小。
const rootValue = 16
const rottWidth = 390
const deviceWidth = document.documentElement.clientWidth
document.documentElement.style.fontSize = deviceWidth * rootValue / rottWidth + 'px'