移动端h5页面屏幕适配rem
rem等比例适配所有屏幕:
相对长度单位,指相对于根元素的字体大小的单位。rem只会相对html的值,不会受到父级的影响,这样的好处在于:从em里的例子来讲,1rem始终会等于8px。使用的时候不需要重新计算rem此时的大小。rem因为是css3增加的,所以ie8或以下请无视。
各种设备屏幕大小不同,分辨率也不同,使用rem适配不同屏幕非常高效,这种方法不同屏幕显示的内容量是一样的,大屏幕显示的内容不会更多。计算根元素字体的大小:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>625</title>
</head>
<script>
(function(){
var currClientWidth,
fontValue,
originWidth;
originWidth = 1080;//ui设计稿的宽度,一般750或640
__resize();
window.addEventListener('resize', __resize, false);
function __resize() {
currClientWidth = document.documentElement.clientWidth;
if (currClientWidth > 768){
currClientWidth = 768;
}
if (currClientWidth < 480){
currClientWidth = 480;
}
fontValue = ((625 * currClientWidth) / originWidth).toFixed(2);
document.documentElement.style.fontSize = fontValue + '%';
}
})();
</script>
<body>
<div style="font-size: .48rem;">
倍率为100是为了方便计算,根元素字体大小为100/(设计稿宽度/屏幕宽度),其中屏幕宽度为物理像素
设置某元素的rem值时,取值为ui设计稿的值除以100,例如,某元素宽为300,那么其css代码为width: 3rem;
</div>
</body>
</html>