postcss-pxtorem
npm install postcss-pxtorem --save-dev
配置文件
// https://github.com/michael-ciniawsky/postcss-load-config module.exports = { "plugins": { "postcss-import": {}, "postcss-url": {}, // to edit target browsers: use "browserslist" field in package.json "autoprefixer": { browsers: ['Android >= 4.0', 'iOS >= 7'] }, "postcss-pxtorem": { viewportWidth: 1920, // (Number) The width of the viewport. viewportHeight: 1024, // (Number) The height of the viewport. unitPrecision: 3, // (Number) The decimal numbers to allow the REM units to grow to. viewportUnit: 'rem', // (String) Expected units. selectorBlackList: [], // (Array) The selectors to ignore and leave as px. minPixelValue: 1, // (Number) Set the minimum pixel value to replace. mediaQuery: false, // (Boolean) Allow px to be converted in media queries. propList: ['*'] } } }
//rem (function () { let orientation = window.matchMedia("(orientation: portrait)"); let width = document.documentElement.getBoundingClientRect().width; //獲取寬度 function onMatchMeidaChange(orientation) { if (orientation.matches) { // 豎屏 width = document.documentElement.getBoundingClientRect().width; //獲取豎屏寬度 setTimeout(() => { // 重新計算豎屏寬度rem autoRootFontSize() }); } else { // 橫屏 width = document.documentElement.getBoundingClientRect().width; //獲取橫屏寬度 setTimeout(() => { // 重新計算橫屏寬度rem autoRootFontSize() }); } } onMatchMeidaChange(orientation); orientation.addListener(onMatchMeidaChange); /* 計算rem */ function autoRootFontSize() { //(當前屏幕寬度,最小寬度為1200)/1920*16px let setSize = Math.max(document.documentElement.getBoundingClientRect().width,1200) / 1920 * 16; //字體默認最大值為16px document.documentElement.style.fontSize = (setSize > 16 ? 16 : setSize) + 'px'; } window.addEventListener('resize', autoRootFontSize); autoRootFontSize(); })();
在App.vue引入:
import "@/assets/js/public/rem.js";
如果不想轉換元素單位可以把px改為Px或者PX。
----------------------------------------------------------------------------------這里是分割線---------------------------------------------------------------------------------------------------
上面是vue-cli2+vue2的安裝和配置方式
那么vue-cli3+vue3中的使用是有區別的:
1、安裝一樣:
npm install postcss-pxtorem --save-dev
2、配置:
1、在根目錄添加文件:postcss.config.js
module.exports = { plugins: { 'autoprefixer': { browsers: ['Android >= 4.0', 'iOS >= 7'] }, 'postcss-pxtorem': { rootValue: 16,//結果為:設計稿元素尺寸/16,比如元素寬320px,最終頁面會換算成 20rem propList: ['*'] } } }
2、在src/assets/js/下添加rem.js【內容同上面的版本】,然后在App.vue中引入: import "@/assets/js/rem.js";
3、重啟看是否生效即可