Vue中rem與postcss-pxtorem的應用詳解
rem 布局
rem是根元素(html)中的font-size值。
rem布局不多贅述,有很多詳細說明rem布局原理的資料。
簡單的說,通過JS獲取設備寬度動態(tài)設定rem值,以實現在不同寬度的頁面中使用rem作為單位的元素自適應的效果。
新建rem.js文件,于main.js中引用
// 設計稿以1920px為寬度,而我把頁面寬度設計為10rem的情況下 const baseSize = 192; // 這個是設計稿中1rem的大小。 function setRem() { // 實際設備頁面寬度和設計稿的比值 const scale = 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
npm install postcss-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進行移動端適配的問題
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
vue+node+socket io實現多人互動并發(fā)布上線全流程
這篇文章主要介紹了vue+node+socket io實現多人互動并發(fā)布上線全流程,本文給大家提到了socket.io相關用法概覽及開發(fā)流程,需要的朋友可以參考下2021-09-09使用form-create動態(tài)生成vue自定義組件和嵌套表單組件
這篇文章主要介紹了使用form-create動態(tài)生成vue自定義組件和嵌套表單組件,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-01-01Vue+Element ui 根據后臺返回數據設置動態(tài)表頭操作
這篇文章主要介紹了Vue+Element ui 根據后臺返回數據設置動態(tài)表頭操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-09-09