关于REM,EM等等单位就不介绍了,百度很多。
这里主要讲:当我们使用vue-cli生成项目然后拿到一个iphone6的设计图的时候,要怎么转换成rem单位。
通过淘宝的flexible动态给html,body添加font-size
通过npm下载flexible,并复制到static文件夹下
npm下载地址
1 2 3 4
| npm i -S amfe-flexible
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no"> <script src="static/amfe-flexible/index.js"></script>
|
如何转换单位
方法1:通过配置IDE
我使用的vscode在插件商城中有一个cssrem的插件,作者是cipchk。安装之后配置一下就行了。
配置vscode:文件 –> 首选项 –> 设置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| { "workbench.startupEditor": "newUntitledFile", "git.enableSmartCommit": true, "files.associations": { "*.vue": "html" }, "terminal.integrated.shell.windows": "C:\\Windows\\System32\\cmd.exe", //这里就是设置基础的font-size,如果设计图是750标准的(iphone6),则设置成75 "cssrem.rootFontSize": 75, // px转rem小数点最大长度,默认:6。 "cssrem.fixedDigits": 3, // 自动移除0开头的前缀,默认:true "cssrem.autoRemovePrefixZero": true }
|
配置之后,在输入px为单位的时候会提示转换成rem的单位。
方法2:通过配置webpack插件实现
postcss-px2rem插件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| npm install postcss-px2rem --save
//vue-cli中的vue-loader.conf.js
'use strict' const utils = require('./utils') const config = require('../config') const isProduction = process.env.NODE_ENV === 'production' const sourceMapEnabled = isProduction ? config.build.productionSourceMap : config.dev.cssSourceMap
module.exports = { loaders: utils.cssLoaders({ sourceMap: sourceMapEnabled, extract: isProduction }), cssSourceMap: sourceMapEnabled, cacheBusting: config.dev.cacheBusting, transformToRequire: { video: ['src', 'poster'], source: 'src', img: 'src', image: 'xlink:href' }, //这里添加postcss的配置 postcss:[ require('postcss-import')(), // 添加@import支持 require('postcss-px2rem')({'remUnit':75,'baseDpr':2}) ] }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| 如果报错,试试修改util.js中的cssLoader配置 // util.js 修改 const cssLoader = { loader: 'css-loader', options: { sourceMap: options.sourceMap } } 为(支持import样式修改rem): const cssLoader = { loader: 'css-loader?importLoaders=1', options: { sourceMap: options.sourceMap } }
|
如若需要原样输出,则在后面加上注释/no/
1 2 3 4 5 6 7 8 9
| .rem2 { margin-top: 30px; height: 375px; width: 375px; border: 1px solid blue;/*no*/ }
这里的1px不会转换成rem单位
|
通过less/sass
使用flexible.js后,再使用less
1 2 3 4 5 6 7 8 9 10 11 12
| //最简实践 <style scoped lang="less"> @rex : 10/750rem; .hello { height: 750*@rex; /* 10rem */ color: red; font-size: 80px; h2 { color: blue; } } </style>
|
使用gulp等工具实现
当然,还可以使用gulp等工具打包实现。
其他
前端工程师需要明白的「像素」
设备像素比devicePixelRatio简单介绍
使用Flexible实现手淘H5页面的终端适配