vue项目 px转换为rem
简介: 开发时不需要自适应,因此使用px开发了整个项目。后期提出自适应需求,但项目中包含style样式的文件很多,考虑到项目现状,全局使用px转rem。注意,使用此方式行内样式中px无法转rem。
(1)在vue项目中的src文件夹下面创建一个config文件夹,在里面创建一个rem.js文件
(2)将下面代码复制到rem.js中
// 基准大小
const baseSize = 16
// 设置 rem 函数
function setRem () {
// 当前页面宽度相对于 1920 宽的缩放比例,可根据自己需要修改。
const scale = document.documentElement.clientWidth / 1920
// 设置页面根节点字体大小
document.documentElement.style.fontSize = (baseSize * Math.min(scale, 2)) + 'px'
}
// 初始化
setRem()
// 改变窗口大小时重新设置 rem
window.onresize = function () {
setRem()
}
(3)在 src 文件夹下的 main.js 中引入
import './config/rem'
(4)在 Vue 项目根目录终端安装postcss-pxtorem
npm install postcss-pxtorem -D
(5)在 Vue 项目文件夹下的 postcss.config.js 中加入
module.exports = {
plugins: {
autoprefixer: {},
"postcss-pxtorem": {
"rootValue": 16,
"propList": ["*"]
}
}
}
注:重启项目之后可能会报错
“ Error: PostCSS plugin postcss-pxtorem requires PostCSS 8.”
意思是:postcss-pxtorem版本为8.0,但实际现有最高版本好像才是5.1.1,
解决方案:安装postcss-pxtorem5.1.1版本
参考文章:
(1)https://blog.csdn.net/zyi200207278017/article/details/125152156
(2)https://blog.csdn.net/k912120/article/details/114678251
使用less
- 安装
npm i less less-loader@5
- vue main.js中引入
import less from 'less';
Vue.use(less);
- .vue文件使用
<style scoped lang="less">
@import url(../assets/css/index.less); // 导入当前页面的less文件
// 设计图是按1920 设计, h1中所有值均取设计图中值,通过.vw函数进行统一换算
.vw (@attr: width, @px) {
@vw: (@px / 1920) * 100;
@{attr}:~"@{vw}vw";
}
@red: red; // 定义变量
h1{
color: @red;
.vw(font-size, 60);
.vw(width, 1080);
}
</style>