在vue项目中使用postcss-px2rem插件把px转变为rem,并配合给html根元素设置fontsize,来实现页面的自适应效果 安装postcss-px2rem插件,目的:把px转变为rem vue.config.js中配置remUnit 通过js改变html的fontsize值 postcss-px2rem插件不能把行内样式进行pxTorem的转换
安装postcss-px2rem插件,目的:把px转变为rem
npm install postcss-px2rem -S
vue.config.js中配置remUnit
const port = process.env.port || 8081 // 端口
module.exports = {devServer: {host: '0.0.0.0',port: port,open: true,},css: {loaderOptions: {css: {},postcss: {plugins: [require('postcss-px2rem')({remUnit: 100})]}}}
}
一直不太明白为什么remUnit设置为100,通过项目中不断的改变remUnit值,发现这里remUnit值是为了把px转换成rem的计算值,即remUnit=100,则1rem=100px,1px=0.01rem当项目中我们在css样式中设置width:750px时,经过[postcss-px2rem]这个插件转换
remStyle:转换后的值(单位:rem)pxStyle:转换前的值(单位:px)remStyle=(pxStyle/remUnit)+'rem'得到:width:7.5rem
通过js改变html的fontsize值
<script type="text/javascript">function getHtmlFontSize() {//获取设备宽度let deviceWidth = document.documentElement.clientWidth || window.innerWidth;console.log("[设备宽度]", deviceWidth);if (deviceWidth >= 750) {deviceWidth = 750;} else if (deviceWidth <= 320) {deviceWidth = 320;}//设置html的字体大小为:1rem=100px;以设计原型750,如果设计稿是640px,font-size=100px,则为deviceWidth/6.4document.documentElement.style.fontSize = (deviceWidth / 7.5) + 'px';}getHtmlFontSize();window.addEventListener("resize", getHtmlFontSize)</script>
postcss-px2rem插件不能把行内样式进行pxTorem的转换