安裝lib-flexible與postcss-px2rem
npm install lib-flexible
或
yarn add lib-flexible
代碼直接使用rem單位不方便閱讀,安裝postcss-px2rem插件可以自動把px轉成rem
npm install postcss-px2rem
或
yarn add postcss-px2rem
使用及配置
在 main.js中直接引入lib-flexible
import "lib-flexible";
在vue.config.js中配置css
css: {
// 啟用 CSS modules
modules: false,
// 是否使用css分離插件
extract: true,
// 開啟 CSS source maps?
sourceMap: false,
// css預設器配置項
loaderOptions: {
css: {},
postcss: {
plugins: [
//remUnit這個配置項的數值根據設計圖來定這個值,便于開發。
//假如設計圖給的寬度是1920,按照24等份來劃分(1920/24),remUnit設置為80(1rem = 80px)
// 需要去改lib-flexible源碼(node_modules\lib-flexible\flexible.js 69行refreshRem()函數)
require("postcss-px2rem")({
remUnit: 80,//1rem = 80px
}),
],
},
},
},
修改lib-flexible的源碼
在node_modules依賴文件中找到flexible.js,修改 refreshRem() 函數。
(node_modules\lib-flexible\flexible.js 大概在69行的refreshRem()函數)
/**
* lib-flexible源碼 修改前
*/
function refreshRem(){
var width = docEl.getBoundingClientRect().width;
if (width / dpr > 540) {
width = 540 * dpr;
}
var rem = width / 10;
docEl.style.fontSize = rem + 'px';
flexible.rem = win.rem = rem;
}
/**
* lib-flexible源碼 修改后
*/
function refreshRem(){
var width = docEl.getBoundingClientRect().width;
if (width / dpr > width) {
width = width * dpr;
}
var rem = width / 24;
docEl.style.fontSize = rem + 'px';
flexible.rem = win.rem = rem;
}
或
function refreshRem(){
var width = docEl.getBoundingClientRect().width;
//屏幕大于1920 小于5760 時
if (width / dpr < 1920) {
width = 1920 * dpr;
}else if(width / dpr > 5760) {
width = 5760 * dpr;
}
var rem = width / 24;
docEl.style.fontSize = rem + 'px';
flexible.rem = win.rem = rem;
}
注意:
行內樣式設置的px無法被轉換成自適應的rem。
lib-flexible給body元素加上了12px的字體大小。
官方解釋:body上設置12 * dpr的font-size值,為了重置頁面中的字體默認值,不然沒有設置font-size的元素會繼承html上的font-size,變得很大。
如果不需要body加字號,可去源碼中進行注銷:
// if (doc.readyState === 'complete') {
// doc.body.style.fontSize = 12 * dpr + 'px';
// } else {
// doc.addEventListener('DOMContentLoaded', function(e) {
// doc.body.style.fontSize = 12 * dpr + 'px';
// }, false);
// }
測試
設置字體為40px
.home {
font-size: 40px;
}
在1920寬度展示:
1920
在960寬度展示:
960