foreword
The version corresponding to the project webpack
is as follows:
npm i [email protected] -D
npm i [email protected] -D
css plugin
amfe-flexible
: According to the device width, modify html
the size of the root element to adapt to different terminals. Configure the scalable layout scheme, mainly 1rem
set to viewWidth/10
.
postcss-pxtorem
: Use the plug-in instead px
of rem postcss
, which can automatically px
convert to rem
and handle some special cases.
Install
npm i [email protected]
npm i [email protected] -D
configuration
amfe-flexible
file main.js
, import plugin
import flexible from 'amfe-flexible'
Vue.use(flexible);
file index.html
configuration
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">
postcss-pxtorem
vue.config.js
orwebpack.config.js
module.exports = {
css: {
loaderOptions: {
postcss: {
plugins: [
require('postcss-pxtorem')({
// 把px单位换算成rem单位
rootValue: 192.0,//rootValue根据设计稿宽度除以10进行设置,这边假设设计稿为1920,即rootValue设为192.0;
unitPrecision: 5,
propList: ['*'],
// selectorBlackList: ['el-',], //
replace: true,
mediaQuery: false,
minPixelValue: 0
})
]
}
}
}
};
16px = 1rem
If you want to set it to16px=1px,1px=0.0625rem
new utils/rem.js
file
// 设置 rem 函数
function setRem() {
// 1920 默认大小16px; 1920px = 120rem ;每个元素px基础上/16
const screenWidth = 1920
const scale = screenWidth / 16
const htmlWidth = document.documentElement.clientWidth || document.body.clientWidth
// 得到html的Dom元素
const htmlDom = document.getElementsByTagName('html')[0]
// 设置根元素字体大小
htmlDom.style.fontSize = htmlWidth / scale + 'px'
}
// 初始化
setRem()
// 改变窗口大小时重新设置 rem
window.onresize = function() {
setRem()
}
main.js
introduce
import '@/utils/rem.js'
vue.config.js
or webpack.config.js
modify
module.exports = {
css: {
loaderOptions: {
postcss: {
plugins: [
require('postcss-pxtorem')({
// 把px单位换算成rem单位
rootValue: 16, // 16px = 1rem
unitPrecision: 5,
propList: ['*'],
// selectorBlackList: ['el-',], //
replace: true,
mediaQuery: false,
minPixelValue: 0
})
]
}
}
}
};
VSCode plugin
Search in the extension cssrem
and install it:
Put the mouse on px
that line, the upper right will be automatically converted to rem
.
browser custom resolution
Take Google as an example, F12 opens "Developer Tools", and the page will appear with the above resolution
Select "Modify..." on the bottom line
Open the "Modify..." dialog box, add a custom device..., pay attention to the selection Desktop
, and finally save to switch