rem 布局
rem是根元素(html)中的font-size值。
rem布局不多贅述,有很多詳細說明rem布局原理的資料。
簡單的說,通過JS獲取設備寬度動態設定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進行移動端適配的問題
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網之家。
新聞熱點
疑難解答