前端响应式布局的最佳实践postcsspluginpx2units

33次阅读

共计 2278 个字符,预计需要花费 6 分钟才能阅读完成。

前端响应式布局的最佳实践 postcss-plugin-px2units

前言:

前端开发页面,需高度还原 UI 设计稿,布局过程中涉及 width、heigth、字体大小等,在适配不同比例屏幕大小时,往往会才用 vw、vh、rem 等来自动适配,本插件主要用于解决:自动计算设计稿 px 到 vw、vh、rem 单位的转换。

实战案例:原 UI 设计稿为 3840px2304px, 需在 1920px1080px 屏幕上等比例缩放

gulp 下简单演示

源码地址:https://gitee.com/jadepam/pos…

新建项目生成 package.json

npm init

安装插件

npm i --save gulp gulp-postcss postcss-plugin-px2units

新建 gulpfile.js

本次案例 vw、vh 用于整体布局,rem 用于设置字体

var gulp = require('gulp');
var postcss = require('gulp-postcss');
var myplugin = require('postcss-plugin-px2units');
gulp.task('css', function () {
  var processors = [
    myplugin({
      viewportWidth: 38.40, // 原设计稿宽度 3840/100
      viewportHeight: 23.04,// 原设计稿高度 2304/100
      rootValue: 200,// 原设计稿高度 3840/1920,此处为 pc 端页面,如为移动端改为 750
    })
  ];
  return gulp.src('./src/*.css')
    .pipe(postcss(processors))
    .pipe(gulp.dest('./dest'));
});

样式文件输入输出

// 输入

html {font-size: 100px;}
@media screen and (max-width: 3840px) {html { font-size: 200px;}
  }
@media screen and (max-width: 1920px) {html { font-size: 100px;}
}
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: flex;
    justify-content: space-between;
    flex-direction: row;
}
.left,.right,.center{
    display: flex;
    justify-content: space-between;
    flex-direction: column;
}
.bottom {
    margin:80rx;
    flex: 1;
}

.left{
   width: 930wx;  
   font-size: 36rx;
}
.right{
    width: 930wx;
    font-size: 36rx;
}
.center{
    width: 1768wx;
    font-size: 64rx; 
}
.left div{height: 640hx;}

.center div:first-child{flex: 1;}
.center div:last-child{height:300hx;}

.right div{height: 984hx;}

// 输出

html {font-size: 100px;}
@media screen and (max-width: 3840px) {html { font-size: 200px;}
  }
@media screen and (max-width: 1920px) {html { font-size: 100px;}
}
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.42rem;
}
.bottom{
    display: flex;
    justify-content: space-between;
    flex-direction: row;
}
.left,.right,.center{
    display: flex;
    justify-content: space-between;
    flex-direction: column;
}
.bottom {
    margin:0.4rem;
    flex: 1;
}

.left{
   width: 24.21875vw;  
   font-size: 0.18rem;
}
.right{
    width: 24.21875vw;
    font-size: 0.18rem;
}
.center{
    width: 46.04167vw;
    font-size: 0.32rem; 
}
.left div{height: 27.77778vh;}

.center div:first-child{flex: 1;}
.center div:last-child{height:13.02083vh;}

.right div{height: 42.70833vh;}

最终效果:


正文完
 0