rem单位

时间:2023-03-08 22:38:30
rem单位

rem单位

rem基础

px是固定单位,不同分辨率下效果不一样,导致网页布局出现偏差。

em是根据父元素来改变字大小

rem是根据根元素html来改变字体大小,只要改变了根元素的font-size就可以改变所有字体的大小。

1,

html{font-size:20px;}

body{width:6rem;}

此处1rem=20px

2,

html{font-size:62.5%;}

body{width:6rem;}

此处1rem=10px;因为默认1rem=16px;

10/16=62.5%

rem跟随分辨率而变化的方法

我们的目的是分辨率不同,字体大小也不同,即适应屏幕分辨率。那么怎样才可以让rem的大小随着分辨率而变化呢?

1,media query,这个不是通用性方法,根据常用的分辨率制定rem。

    html {font-size : 20px;}
@media only screen and (min-width: 401px){
html {font-size: 25px !important;}
}
@media only screen and (min-width: 428px){
html {font-size: 26.75px !important;}
}
@media only screen and (min-width: 481px){
html {font-size: 30px !important; }
}
@media only screen and (min-width: 569px){
html {font-size: 35px !important; }
}
@media only screen and (min-width: 641px){
html {font-size: 40px !important; }
}

2,js方法

 <script>
(function (doc, win) {
var docEl = doc.documentElement,
resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
recalc = function () {
var clientWidth = docEl.clientWidth;
if (!clientWidth) return;
clientWidth=(clientWidth>640)?640:clientWidth;
docEl.style.fontSize = 20 * (clientWidth / 320) + 'px';
}; if (!doc.addEventListener) return;
win.addEventListener(resizeEvt, recalc, false);
doc.addEventListener('DOMContentLoaded', recalc, false);
})(document, window);
</script>

其他布局方法

1,流式布局

宽度用百分比;高度用px单位,即高度固定。大分辨率下变形。

当然可以让高度值为rem单位;宽度也要注意兼容性问题。

2,限定宽度

固定的320px,大分辨率下,两边留白。不提倡。

3,响应式

不了解

道听途说:直接从web page直接转换为web app。对大公司来说工作量大,维护难,中小企业可以使用,节约成本。

4,设置viewport,缩放

<meta name="viewport" content="width=320,maximum-scale=1.3,user-scalable=no" />

效率高,效果也不错。