在html使用了网上阿里的函数来计算根元素的字体(固然能够写在其余地方,只要生效就能够)css
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width" /> <title>xxx</title> <base href="./"> <link rel="icon" type="image/x-icon" href="favicon.ico"> <style type="text/css"> .icon { width: 1em; height: 1em; vertical-align: -0.15em; fill: currentColor; overflow: hidden; } </style> </head> <body> <app-root></app-root> <!--调试插件--> <!--<script src="http://mtestzhanqi.artqiyi.com/views/common/libs/vconsole.min.js "></script>--> <script> /* * 根据屏幕宽度改变根元素字体 */ (function(doc, win) { var docEl = doc.documentElement, resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize', recalc = function() { var clientWidth = docEl.clientWidth; if (!clientWidth) return; docEl.style.fontSize = window.screen.width / 10 + 'px'; }; if (!doc.addEventListener) return; win.addEventListener(resizeEvt, recalc, false); doc.addEventListener('DOMContentLoaded', recalc, false); })(document, window); </script> </body> </html>
这里主要使用了函数计算根元素字体,将屏幕分红了10分,在iphone6下面根元素字体就是37.5px;html
这是使用了less的unit函数来添加单位,将全部的须要转化的css都写到一个公共的less文件里面,经过@import导入进去。(这里只是粘贴了一部分)vue
.fs(@px) { font-size: unit(@px / 37.5, rem); } /*----- 宽度 -----*/ .w(@px) { width: unit(@px / 37.5, rem); } /*----- 高度 -----*/ .h(@px) { height: unit(@px / 37.5, rem); } /*----- 行高 -----*/ .lh(@px) { line-height: unit(@px / 37.5, rem); } /*----- 背景尺寸 -----*/ .b_s(@px, @px) { -webkit-background-size: unit(@px / 37.5, rem) unit(@px / 37.5, rem); background-size: unit(@px / 37.5, rem) unit(@px / 37.5, rem); } /** * [背景尺寸,设置宽度,高度auto] */ .b_s1(@px) { -webkit-background-size: unit(@px / 37.5, rem) auto; background-size: unit(@px / 37.5, rem) auto; } .b_s2(@px) { -webkit-background-size: auto unit(@px / 37.5, rem); background-size: auto unit(@px / 37.5, rem); } /*----- margin -----*/ .mt(@px) { margin-top: unit(@px / 37.5, rem); } .mr(@px) { margin-right: unit(@px / 37.5, rem); } .mb(@px) { margin-bottom: unit(@px / 37.5, rem); } .ml(@px) { margin-left: unit(@px / 37.5, rem); }
将iphone6的屏幕分红10分,因此就除了37.5,用unit函数来添加单位(这里是相对iphone6的屏幕的,相信大部分公司移动端的设计图都是根据iphone6设计的)。web
@import "../less/bass.less"; .sort-title { .fs(17); color: @color0; font-family: PingFang-SC-Medium; .mt(20); .mb(15); }
.fs, .mt这些就是less的函数,最终编译好的文件就是rem了。(总之,在iphon6或者iphone7,屏幕是376px,不管你上面怎么分配比例,在chrome里面审查你编译后的css,鼠标放到元素上会显示大小,这时和你设计图上的大小相等就能够。)chrome
本人感受这样仍是比较方便的,不用像那样设置根元素100px,而后根据sublime的插件来计算,或者更复杂的计算等等。咱们项目使用angular4,angular4能够自动编译less,只需向上面那样直接调用函数就能够,并且能够作一些运算,仍是比较方便的,固然vue里面你只要安装less插件,就能够让vue-cli来编译了,若是这些你都没用,你还能够经过Koala来编译成css,经过link来引入。vue-cli