前言
根据 W3C 规范中对 1rem 的定义:
1rem 与等于根元素 font-size 的计算值。当明确规定根元素的 font-size 时,rem 单位以该属性的初始值作参照。这就意味着 1rem 等于 html 元素的字体大小(大部分浏览器根元素的字体大小为16px)
兼容性
ios:6.1系统以上都支持
android:2.1系统以上都支持
大部分主流浏览器都支持,可以安心的往下看了。
rem:(font size of the root element)
意思就是根据网页的根元素来设置字体大小,和em(font size of the element)的区别是,em是根据其父元素的字体大小来设置,而rem是根据网页的跟元素(html)来设置字体大小的,举一个简单的例子,
现在大部分浏览器IE9+,Firefox、Chrome、Safari、Opera ,如果我们不修改相关的字体配置,都是默认显示font-size是16px,即
html {font-size:16px;}
那么如果我们想给一个P标签设置12px的字体大小,那么用rem来写就是
p {font-size: 0.75rem; //12÷16=0.75(rem)}
使用rem这个字体单位进行适配,就是利用它作为一个全局字体固定参照单位的特性。如果改变html元素的字体大小,rem的值也就跟着改变,对应的其他使用rem的布局尺寸,也会跟着改变,从而达到适配的目的,保证比例一致。 **所以rem不仅可以适用于字体,同样可以用于width height margin这些样式的单位。**
rem适配具体实现方案:
设计稿尺寸宽度为750px,如果设计稿是640px,下边js会自动计算rem的值(比如rem:75px -> rem: 64px),具体的尺寸rem不用调整(例如 padding: 1.5rem,不用调整,这是一个比例大小),对应的元素大小px值会根据新的rem(比如rem: 64px, padding等于 1.5 * 64)改变,从而按照比例适配。
index.html
<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><title>rem适配</title><script>;(function(win, lib) {var doc = win.document;var docEl = doc.documentElement;var metaEl = doc.querySelector('meta[name="viewport"]');var flexibleEl = doc.querySelector('meta[name="flexible"]');var dpr = 0;var scale = 0;var tid;var flexible = lib.flexible || (lib.flexible = {});if (metaEl) {console.warn('将根据已有的meta标签来设置缩放比例');var match = metaEl.getAttribute('content').match(/initial-scale=([d.]+)/);if (match) {scale = parseFloat(match[1]);dpr = parseInt(1 / scale);}} else if (flexibleEl) {var content = flexibleEl.getAttribute('content');if (content) {var initialDpr = content.match(/initial-dpr=([d.]+)/);var maximumDpr = content.match(/maximum-dpr=([d.]+)/);if (initialDpr) {dpr = parseFloat(initialDpr[1]);scale = parseFloat((1 / dpr).toFixed(2)); }if (maximumDpr) {dpr = parseFloat(maximumDpr[1]);scale = parseFloat((1 / dpr).toFixed(2)); }}}if (!dpr && !scale) {var isAndroid = win.navigator.appVersion.match(/android/gi);var isIPhone = win.navigator.appVersion.match(/iphone/gi);var devicePixelRatio = win.devicePixelRatio;if (isIPhone) {// iOS下,对于2和3的屏,用2倍的方案,其余的用1倍方案if (devicePixelRatio >= 3 && (!dpr || dpr >= 3)) {dpr = 3;} else if (devicePixelRatio >= 2 && (!dpr || dpr >= 2)){dpr = 2;} else {dpr = 1;}} else {// 其他设备下,仍旧使用1倍的方案dpr = 1;}scale = 1 / dpr;}docEl.setAttribute('data-dpr', dpr);if (!metaEl) {metaEl = doc.createElement('meta');metaEl.setAttribute('name', 'viewport');metaEl.setAttribute('content', 'initial-scale=' + scale + ', maximum-scale=' + scale + ', minimum-scale=' + scale + ', user-scalable=no');if (docEl.firstElementChild) {docEl.firstElementChild.appendChild(metaEl);} else {var wrap = doc.createElement('div');wrap.appendChild(metaEl);doc.write(wrap.innerHTML);}}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;}win.addEventListener('resize', function() {clearTimeout(tid);tid = setTimeout(refreshRem, 300);}, false);win.addEventListener('pageshow', function(e) {if (e.persisted) {clearTimeout(tid);tid = setTimeout(refreshRem, 300);}}, false);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);}refreshRem();flexible.dpr = win.dpr = dpr;flexible.refreshRem = refreshRem;flexible.rem2px = function(d) {var val = parseFloat(d) * this.rem;if (typeof d === 'string' && d.match(/rem$/)) {val += 'px';}return val;}flexible.px2rem = function(d) {var val = parseFloat(d) / this.rem;if (typeof d === 'string' && d.match(/px$/)) {val += 'rem';}return val;}})(window, window['lib'] || (window['lib'] = {}));</script></head><body><noscript><strong>We're sorry but rem适配 doesn't work properly without JavaScript enabled. Please enable it to continue.</strong></noscript><div id="app"></div><!-- built files will be auto injected --></body></html>
helper.scss
$remBase: 75;$primaryColor: #ffd633;@function px2rem($px) {@return ($px / $remBase) * 1rem;}%textOverflow {width: 100%;white-space: nowrap;text-overflow: ellipsis;overflow: hidden;}// @include borderLineTop('top', color)@mixin borderLine($mode: 'top', $color: #e5e5e5) {position: relative;@if $mode == 'top' {&::before {// 实现1物理像素的下边框线content: '';position: absolute;z-index: 1;pointer-events: none;background-color: $color;height: 1px;left: 0;right: 0;top: 0;@media only screen and (-webkit-min-device-pixel-ratio: 2) {-webkit-transform: scaleY(0.5);-webkit-transform-origin: 50% 0%;}}}@if $mode == 'bottom' {&::after {// 实现1物理像素的下边框线content: '';position: absolute;z-index: 1;pointer-events: none;background-color: $color;height: 1px;left: 0;right: 0;bottom: 0;@media only screen and (-webkit-min-device-pixel-ratio: 2) {-webkit-transform: scaleY(0.5);-webkit-transform-origin: 50% 0%;}}}}@mixin borderRadius($radius) {border-top-left-radius: px2rem($radius);border-top-right-radius: px2rem($radius);border-bottom-left-radius: px2rem($radius);border-bottom-right-radius: px2rem($radius);}// @include banner(100)@mixin banner($height) {position: relative;padding-top: percentage($height/750); // 使用padding-topheight: 0;overflow: hidden;img {width: 100%;height: auto;position: absolute;left: 0;top: 0;}}$spaceamounts: (5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 100);$sides: (top, bottom, left, right);@each $space in $spaceamounts {@each $side in $sides {.m-#{str-slice($side, 0, 1)}-#{$space} {margin-#{$side}: #{px2rem($space)} !important;}.p-#{str-slice($side, 0, 1)}-#{$space} {padding-#{$side}: #{px2rem($space)} !important;}}}.flex-center {display: flex;align-items: center;}@mixin font-dpr($font-size){font-size: $font-size;[data-dpr="2"] & {font-size: $font-size * 2;}[data-dpr="3"] & {font-size: $font-size * 3;}}
App.vue, 使用px2rem进行转换
<style lang="scss">@import "@/assets/style/helper.scss";#nav {padding: px2rem(24);a {font-size: px2rem(24);font-weight: bold;color: #2c3e50;&.router-link-exact-active {color: #42b983;}}}</style>