vue3中用 amfe-flexible + postcss-pxtorem
amfe-flexible:根據(jù)屏幕寬度,自動設(shè)置html的font-size
postcss-pxtorem:自動將px單位轉(zhuǎn)換成rem
- 首先需要在 index.html文件中的header標(biāo)簽里次氨,以消除很多標(biāo)簽自帶的padding和marging稍走,
設(shè)置最大寬度需要在index.html和app.vue里面同時設(shè)置最大寬度
<style>
/*消除很多標(biāo)簽自帶的padding和marging */
* {
margin: 0;
padding: 0;
}
/*設(shè)置背景顏色*/
body {
background-color: #f4fdff;
}
/*設(shè)置最大寬度 */
@media screen and (min-width: 500px) {
html {
font-size: 50px !important;
}
}
/*設(shè)置最小寬度 */
@media screen and (max-width: 320px) {
html {
font-size: 32px !important;
}
}
</style>
- 再次為了使?jié)嵜孢m配大屏巨坊,需要在 app.vue里面設(shè)置
#app {
margin: 0 auto; /* 居中顯示 */
max-width: 420px; /* 設(shè)置最大寬度顯示 */
}
- 其次 在index.html文件中 設(shè)置這段的目的是設(shè)置視口寬度艇棕,不允許用戶縮放
<!-- width: 設(shè)置布局視口的寬度 device-width是獲取用戶設(shè)備的寬度 -->
<meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1, minimum-scale=1,user-scalable=no">
1.引入amfe-flexible
npm i -S amfe-flexible
2. 引入 postcss-pxtorem
npm install postcss-pxtorem --save-dev
3. 安裝完后我們先在main.js中引入amfe-flexible
import 'amfe-flexible'
4 接著在項(xiàng)目"根目錄"新建一個postcss.config.js文件
5. 或者可在vue.config.js纷铣、.postcssrc.js、postcss.config.js其中之一配置矢渊,權(quán)重從左到右降低,沒有則新建文件枉证,只需要設(shè)置其中一個即可
- 1矮男、 rootValue根據(jù)設(shè)計(jì)稿寬度除以10進(jìn)行設(shè)置,這邊假設(shè)設(shè)計(jì)稿為375室谚,即rootValue設(shè)為37.5毡鉴;
- 2、propList是設(shè)置需要轉(zhuǎn)換的屬性秒赤,這邊*為所有都進(jìn)行轉(zhuǎn)換猪瞬。
1、在vue.config.js配置如下
module.exports = {
css: {
loaderOptions: {
postcss: {
plugins: [
require('postcss-pxtorem')({
rootValue: 37.5,
propList: ['*']
})
]
}
}
},
}
2入篮、或在.postcssrc.js或postcss.config.js中配置如下:
module.exports = {
"plugins": {
autoprefixer: {},
'postcss-pxtorem': {
rootValue: 75, //設(shè)計(jì)稿寬度的1/10陈瘦。
propList: ['*'] //需要做轉(zhuǎn)化處理的屬性,如 height weidth margin 等崎弃,*表示全部
}
}
}
5. 配置完之后我們就可以在項(xiàng)目中以px為單位去開發(fā)了甘晤,是的,不用我們手動敲rem轉(zhuǎn)換去開發(fā)了饲做,PS設(shè)計(jì)稿的寬度以750px為基準(zhǔn),否則需要自己調(diào)一下遏弱,開發(fā)時稿子是1px盆均,你就寫1px就好了,插件會幫我們換算成rem漱逸。
6實(shí)際的項(xiàng)目中泪姨,你測量的px是多少,就直接寫多少px,轉(zhuǎn)化為rem,無需自己計(jì)算
感謝以下鏈接支持
https://blog.csdn.net/weixin_42063951/article/details/127734001
https://blog.csdn.net/Orange71234/article/details/131329898