一、px
- 在页面的布局当中,px是最常见的单位.
- px是物理像素,根据电脑分辨率来进行计算
- 不会存在继承问题
二、em
- 根据字体大小来进行计算
- 如果存在有嵌套->字体 = 父级字体大小 + 子级字体大小
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no">
<title>Document</title>
<style>
body{
font-size: 20px;
}
div{
background-color: #ccc;
width:5em; /*100px;*/
}
</style>
</head>
<body>
<div>心游于艺,道不远人</div>
<p style="font-size:2em;">
心<span style="font-size:2em;">游于艺</span>道不远人
</p>
</body>
</html>
- p标签的父级是body(字体大小是20px),所以是2 x 20=40px
span标签的父级是p(字体大小是40px),所以自己是2 x 40=80px.
三、rem
- 字体大小默认根元素大小
- 所有的rem中都是根据根元素设置的font-size来进行计算
- 通过媒体查询或者通过js获取屏幕viewport来进行字体的计算
//媒体查询方式进行根元素字体大小的计算
<style type="text/css">
@media screen and (min-width: 320px) {html{font-size:50px;}}
@media screen and (min-width: 360px) {html{font-size:56.25px;}}
@media screen and (min-width: 375px) {html{font-size:58.59375px;}}
@media screen and (min-width: 400px) {html{font-size:62.5px;}}
@media screen and (min-width: 414px) {html{font-size:64.6875px;}}
@media screen and (min-width: 440px) {html{font-size:68.75px;}}
@media screen and (min-width: 480px) {html{font-size:75px;}}
@media screen and (min-width: 520px) {html{font-size:81.25px;}}
@media screen and (min-width: 560px) {html{font-size:87.5px;}}
@media screen and (min-width: 600px) {html{font-size:93.75px;}}
@media screen and (min-width: 640px) {html{font-size:100px;}}
@media screen and (min-width: 680px) {html{font-size:106.25px;}}
@media screen and (min-width: 720px) {html{font-size:112.5px;}}
@media screen and (min-width: 760px) {html{font-size:118.75px;}}
@media screen and (min-width: 800px) {html{font-size:125px;}}
@media screen and (min-width: 960px) {html{font-size:150px;}}
</style>
//js获取viewport来进行根元素字体大小的计算
<script type="text/javascript">
(function (doc, win) {
var docEl = doc.documentElement,
resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
recalc = function (){
var clientWidth = docEl.clientWidth;
if (!clientWidth) return;
if(clientWidth>=640){//640是以phone5s的分辨率,可以自行修改
docEl.style.fontSize = '100px';
}else{
docEl.style.fontSize = 100 * (clientWidth / 640) + 'px';//同上
}
};
if(!doc.addEventListener) return;
win.addEventListener(resizeEvt, recalc, false);
doc.addEventListener('DOMContentLoaded', recalc, false);
})(document, window);
</script>