当前位置: 首页 > Web前端 > CSS

rem和postcss-pxtorem在Vue中的应用

时间:2023-03-31 12:02:55 CSS

rem布局rem是根元素(html)中的font-size值。关于rem布局的细节介绍不多,详细介绍rem布局原理的资料很多。简单的说就是通过JS获取设备宽度来动态设置rem值,实现不同宽度页面中以rem为单位的元素的自适应效果。新建一个rem.js文件,在main.js中引用//设计稿宽度为1920px,我设计页面宽度为10remconstbaseSize=192;//这是设计稿中1rem的大小。functionsetRem(){//实际设备页面宽度与设计稿宽度的比例constscale=document.documentElement.clientWidth/1920;//计算实际的rem值赋给html的font-sizedocument.documentElement.style.fontSize=(baseSize*scale)+'px';}setRem();window.addEventListener('resize',()=>{setRem();});postcss-pxtorempostcss-pxtorem是一个PostCSS插件,用于像素单位生成rem单位。安装一个新的Vue项目安装postcss-pxtoremnpminstallpostcss-pxtorem--save-devconfiguration可以在3个地方添加配置,配置文件位于vue项目的根目录下。如果该文件不存在,您可以自己创建它。其中最重要的是这个:rootValue(Number)根元素的值,即1rem的值,用于设计稿元素size/rootValue如rootValue=192,在css中,width:960px;最终会转换为width:5rem;还有一些其他的配置:propList(Array)属性需要转换成单位。必须完全匹配并使用*来选择所有属性。例子:['*']在句首和句尾使用*(['*position*']会匹配background-position-y)使用!配置不匹配的属性。示例:['*','!letter-spacing']组合使用。示例:['*','!font*']minPixelValue(Number)可以替换的最小像素。unitPrecision(Number)rem单位的小数位数上限。完整的细节可以看官方文档weightvue.config.js>.postcssrx.js>postcss.config.js其中postcssrc.js和postcss。config.js可以热更新,vue.config.js中的修改需要重启devServer配置示例vue.config.jsmodule.exports={//...其他配置css:{loaderOptions:{postcss:{plugins:[require('postcss-pxtorem')({rootValue:192,minPixelValue:2,propList:['*'],})]}}},}.postcssrx.jsmodule.exports={plugins:{'postcss-pxtorem':{rootValue:16,minPixelValue:2,propList:['*'],}}}postcss.config.jsmodule.exports={plugins:{'postcss-pxtorem':{rootValue:192,minPixelValue:2,propList:['*'],}}}参考Github官方仓库:postcss-pxtoremvue3.0中使用的postcss-pxtorem关于Vue使用postcss-pxtorem进行移动端适配