欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Vue中rem與postcss-pxtorem的應(yīng)用詳解

 更新時(shí)間:2019年11月20日 10:33:25   作者:OceanZH  
這篇文章主要介紹了Vue中rem與postcss-pxtorem的應(yīng)用詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧

rem 布局

rem是根元素(html)中的font-size值。

rem布局不多贅述,有很多詳細(xì)說(shuō)明rem布局原理的資料。

簡(jiǎn)單的說(shuō),通過(guò)JS獲取設(shè)備寬度動(dòng)態(tài)設(shè)定rem值,以實(shí)現(xiàn)在不同寬度的頁(yè)面中使用rem作為單位的元素自適應(yīng)的效果。

新建rem.js文件,于main.js中引用

// 設(shè)計(jì)稿以1920px為寬度,而我把頁(yè)面寬度設(shè)計(jì)為10rem的情況下

const baseSize = 192; // 這個(gè)是設(shè)計(jì)稿中1rem的大小。
function setRem() {
  // 實(shí)際設(shè)備頁(yè)面寬度和設(shè)計(jì)稿的比值
  const scale = document.documentElement.clientWidth / 1920;
  // 計(jì)算實(shí)際的rem值并賦予給html的font-size
  document.documentElement.style.fontSize = (baseSize * scale) + 'px';
}
setRem();
window.addEventListener('resize', () => {
  setRem();
});

postcss-pxtorem

postcss-pxtorem是PostCSS的插件,用于將像素單元生成rem單位。

安裝

新建Vue項(xiàng)目
安裝 postcss-pxtorem

npm install postcss-pxtorem --save-dev

配置

可以通過(guò)3個(gè)地方來(lái)添加配置,配置文件皆位于vue 項(xiàng)目根目錄中,若文件不存在可以自行建立。

其中最重要的是這個(gè):

rootValue (Number)

  • 根元素的值,即1rem的值
  • 用于設(shè)計(jì)稿元素尺寸/rootValue
  • 比如 rootValue = 192 時(shí),在css中width: 960px; 最終會(huì)換算成width: 5rem;

還有一些其他的配置:

propList (Array) 需要做單位轉(zhuǎn)化的屬性.

  • 必須精確匹配
  • 用 * 來(lái)選擇所有屬性. Example: ['*']
  • 在句首和句尾使用 * (['*position*'] 會(huì)匹配 background-position-y)
  • 使用 ! 來(lái)配置不匹配的屬性. Example: ['*', '!letter-spacing']
  • 組合使用. Example: ['*', '!font*']

minPixelValue(Number) 可以被替換的最小像素.

unitPrecision(Number) rem單位的小數(shù)位數(shù)上限.

完整的可以看官方文檔

權(quán)重

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倉(cāng)庫(kù):postcss-pxtorem
vue3.0中使用postcss-pxtorem
關(guān)于vue利用postcss-pxtorem進(jìn)行移動(dòng)端適配的問(wèn)題

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論