Vue中rem与postcss-pxtorem的应用详解
rem布局
rem是根元素(html)中的font-size值。
rem布局不多赘述,有很多详细说明rem布局原理的资料。
简单的说,通过JS获取设备宽度动态设定rem值,以实现在不同宽度的页面中使用rem作为单位的元素自适应的效果。
新建rem.js文件,于main.js中引用
//设计稿以1920px为宽度,而我把页面宽度设计为10rem的情况下 constbaseSize=192;//这个是设计稿中1rem的大小。 functionsetRem(){ //实际设备页面宽度和设计稿的比值 constscale=document.documentElement.clientWidth/1920; //计算实际的rem值并赋予给html的font-size document.documentElement.style.fontSize=(baseSize*scale)+'px'; } setRem(); window.addEventListener('resize',()=>{ setRem(); });
postcss-pxtorem
postcss-pxtorem是PostCSS的插件,用于将像素单元生成rem单位。
安装
新建Vue项目
安装postcss-pxtorem
npminstallpostcss-pxtorem--save-dev
配置
可以通过3个地方来添加配置,配置文件皆位于vue项目根目录中,若文件不存在可以自行建立。
其中最重要的是这个:
rootValue(Number)
- 根元素的值,即1rem的值
- 用于设计稿元素尺寸/rootValue
- 比如rootValue=192时,在css中width:960px;最终会换算成width:5rem;
还有一些其他的配置:
propList(Array)需要做单位转化的属性.
- 必须精确匹配
- 用*来选择所有属性.Example:['*']
- 在句首和句尾使用*(['*position*']会匹配background-position-y)
- 使用!来配置不匹配的属性.Example:['*','!letter-spacing']
- 组合使用.Example:['*','!font*']
minPixelValue(Number)可以被替换的最小像素.
unitPrecision(Number)rem单位的小数位数上限.
完整的可以看官方文档
权重
vue.config.js>.postcssrx.js>postcss.config.js
其中postcssrc.js和postcss.config.js可以热更新,vue.config.js中做的修改要重启devServer
配置示例
vue.config.js
module.exports={ //...其他配置 css:{ loaderOptions:{ postcss:{ plugins:[ require('postcss-pxtorem')({ rootValue:192, minPixelValue:2, propList:['*'], }) ] } } }, }
.postcssrx.js
module.exports={ plugins:{ 'postcss-pxtorem':{ rootValue:16, minPixelValue:2, propList:['*'], } } }
postcss.config.js
module.exports={ plugins:{ 'postcss-pxtorem':{ rootValue:192, minPixelValue:2, propList:['*'], } } }
Reference
官方Github仓库:postcss-pxtorem
vue3.0中使用postcss-pxtorem
关于vue利用postcss-pxtorem进行移动端适配的问题
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。