前端開發頁面,需高度還原UI設計稿,佈局過程當中涉及width、heigth、字體大小等,在適配不一樣比例屏幕大小時,每每會才用vw、vh、rem等來自動適配,本插件主要用於解決:自動計算設計稿px到vw、vh、rem單位的轉換。css
實戰案例:使用Flex佈局、grid佈局、視口單元rem、vw和wh來適應多屏問題,原UI設計稿爲3840px2304px,需在1920px1080px屏幕上等比例縮放html
源碼地址:https://gitee.com/jadepam/pos...前端
npm init
npm i --save gulp gulp-postcss postcss-plugin-px2units
本次案例vw、vh用於總體佈局,rem用於設置字體git
var gulp = require('gulp'); var postcss = require('gulp-postcss'); var myplugin = require('postcss-plugin-px2units'); gulp.task('css', function () { var processors = [ myplugin({ viewportWidth: 3840, //原設計稿寬度3840 viewportHeight: 2304,//原設計稿高度2304 }) ]; return gulp.src('./src/*.css') .pipe(postcss(processors)) .pipe(gulp.dest('./dest')); });
//輸入npm
html { font-size: 100wx;} /* 100/1920 */ body{ padding: 0; margin: 0; display: flex; height: 100vh; flex-direction: column; justify-content: space-around; background: yellow; text-align: center; } div{ border: 1px solid black; } .top{ height: 217hx; font-size: 84rx;/*/設計稿字體大小*/ } .bottom{ display: grid; grid-template-columns: 930fr 1768fr 930fr; /* //設計稿寬度 */ font-size: 84wx;/*/設計稿字體大小*/ } .left div,.right div,.center div{ margin: 40wx; } .bottom { margin:80wx; flex: 1; } .left{ display: grid; grid-template-rows: repeat(3, 640fr); } .center{ display: grid; grid-template-rows: 1fr auto; } .right{ display: grid; grid-template-rows: repeat(2, 984fr); }
//輸出json
html { font-size: 2.60417vw;} /* 100/1920 */ body{ padding: 0; margin: 0; display: flex; height: 100vh; flex-direction: column; justify-content: space-around; background: yellow; text-align: center; } div{ border: 1px solid black; } .top{ height: 9.4184vh; font-size: 0.84rem;/*/設計稿字體大小*/ } .bottom{ display: grid; grid-template-columns: 930fr 1768fr 930fr; /* //設計稿寬度 */ font-size: 2.1875vw;/*/設計稿字體大小*/ } .left div,.right div,.center div{ margin: 1.04167vw; } .bottom { margin:2.08333vw; flex: 1; } .left{ display: grid; grid-template-rows: repeat(3, 640fr); } .center{ display: grid; grid-template-rows: 1fr auto; } .right{ display: grid; grid-template-rows: repeat(2, 984fr); }
最終效果:gulp