关于px转rem自适应

309 阅读1分钟

calc(100vw * 16 / 1920)

 写在css里,16是字体大小,1920是屏幕大小 

下载插件使用

1-  npm i postcss-pxtorem
    npm i px2rem-loader
2-  在main.css中
    修改html,body{font-size :1px}
3-  在utils下创建rem.js,引入main.js

const baseSize = 16 //
function setRem(){
    let html = document.getElementsByTagName("html")[0];
    if (window.innerWidth * window.innerHeight <= 1920 * 1080) {
        html.style.fontSize = (window.innerWidth * window.innerHeight) / 1920 / 1080 + "px";
    } else {
        html.style.fontSize = (window.innerWidth * window.innerHeight) / 1920 / 1080 / 2 + "px";
    }
}
setRem()
// 两种监听改变根元素大小
window.onresize = function(){
    console.log('q go b ');

    setRem()
}
// window.addEventListener('resize',()=>{
//     console.log('q go b ');
//     setRem()
// })

4-配置vue.config.js


module.exports = {
    css:{
        loaderOptions:{
            postcss:{
                Plugin:[
                    require("postcss-pxtorem")({
                        rootValue:16,
                        unitPrecision:5,
                        propList:["*"],
                        exclude:/(node_module)/,
                        mediaQuery:false,
                        selectorBlackList:".el",
                        minPixelValue:1
                    })
                ]
            }
        }
    }
}

5-然后就可以直接写相应的16rem 就可以了