em
em是font size of the element的简称,是指相对于父元素的字体大小的单位。父元素的字体设置大一些,那么子元素的1em就大一些。
例如:
外层的 “专家团”字体大小25.6px:
内层的 “专家团”字体大小40.96px:
rem
rem是font size of the root element的简称,是相对于根元素的字体大小的单位。
在根元素的font-size指定时,rem单位是指属性的初始值。
这意味着1rem等于html元素的字体大小(对于大多数浏览器而言,默认值是16px)。
例如:
rem单位与px之间的转换
假设根元素的字体大小是16px,那么:
10px=0.625rem
14px=0.875rem
16px=1rem
24px=1.5rem
可以看到,这些数值计算起来不方便。因此,可以使用一个叫62.5的方式来解决这个问题,即设置根元素的字体大小为62.5%:
html {
/* 16px*62.5%=10px */
font-size: 62.5%;
}
其它的元素就很好设置了(因为基于10像素来设置),例如:
body {
/* 10px*1.4=14px */
font-size: 1.4rem;
}
h1 {
/* 10px*2.4=24px */
font-size: 2.4rem;
}
正常的rem布局的方法
想要字体大小随着屏幕宽度变化,在小屏幕上字体小一些,在大屏幕上,字体大一些。
使用rem布局:
- 加载js文件
- 所有数值除以100
- 使用rem单位
假设文件布局:
rem375.js文件的内容:
(function(doc, win) {
//rem布局
var reCreateStyle = function() {
var style;
if(style = document.getElementById("forhtml")) {
style.parentNode.removeChild(style);
}
style = document.createElement("style");
style.id = "forhtml";
var head=document.head||document.getElementsByTagName("head")[0];
head.appendChild(style);
var fontSize = 100.00 * (parseFloat(document.documentElement.clientWidth, 10)) / 375.00;
style.appendChild(document.createTextNode("html{font-size:" + fontSize + "px !important;}"));
};
var docEl = doc.documentElement,
resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
recalc = function() {
reCreateStyle();
},
loadcalc = function() {
reCreateStyle();
var bodyEl = document.body;
if(hasClass(bodyEl, "loading")) {
removeClass(bodyEl, "loading");
}
}
recalc();
if(!doc.addEventListener) return;
win.addEventListener(resizeEvt, loadcalc, false);
doc.addEventListener('DOMContentLoaded', loadcalc, false);
})(document, window);
htm文件:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
h1 {
/* 想在375像素的时候,字体大小是20像素,那么就20/100=0.2,然后加上rem单位 */
font-size: 0.2rem;
}
</style>
</head>
<body>
<h1>rem布局演示</h1>
<!-- 引入js文件 -->
<script src="js/rem375.js"></script>
</body>
</html>
如果手机屏幕宽度为375像素,那么字体大小显示为20px:
如果手机屏幕宽度变大,那么字体也随着变大: