移动端自适应+浏览器兼容
使用postcss-px2rem
原理:
- 浏览器兼容
posscss会将本地的css预处理文件进行打包加上各种浏览器的前缀以做到浏览器兼容 - px2rem
使用该插件后达到的效果是:按照视觉稿的像素值写css样式,且能做到不同设备的样式自适应。其原理是通过将你写的px转换为rem,并指定根元素的font-size与屏幕的比例与remUnit和视觉稿的比例相同,具体操作如下:
当视觉稿的宽度为750px时,
在webpack中的配置:
postcss: function() {
return [px2rem({remUnit: 75})]; // 视觉稿的1/10
}
在index.html中指定:
font-size为document宽度的1/10
<script>document.getElementsByTagName('html')[0].style.fontSize = (document.documentElement.clientWidth || document.body.clientWidth) /10 + 'px';</script>
iPhoneX适配
iPhoneX 的分辨率:2436 * 1125 || pt: 812 * 375 || dpr: 3
iPhoneXr的分辨率:1792 * 828 || pt: 896 * 414 || dpr: 3
iPhoneXs 的分辨率: 2436 * 1125 || pt: 812 * 375 || dpr: 3
iPhoneXs Max 的分辨率:2688 * 1242 || pt: 896 * 414 || dpr: 3
可以看到xs和x的分辨率和dpr是相同的,xr和xsMax的分辨率和dpr是相同的,因此,css可以这样适配:
@media only screen and (device-width: 375px) and (device-height: 812px) and (-webkit-device-pixel-ratio: 3) {
/* 适配iPhoneX,iPhoneXs */
}
@media only screen and (device-width: 414px) and (device-height: 896px) and (-webkit-device-pixel-ratio: 3) {
/* 适配iPhoneXr,iPhoneXs Max */
}