css种的单位整体可以分成两类:
绝对长度单位(Absolute length units);
相对长度单位(Relative length units)
1. 绝对单位( Absolute length units )
![](https://img.haomeiwen.com/i27388007/3e01aa0cef48c17b.png)
2. CSS中的相对单位( Relative length units )
![](https://img.haomeiwen.com/i27388007/86d17ff815a316f4.png)
2.1. em
![](https://img.haomeiwen.com/i27388007/a6e8369e0fcc8a88.png)
相对于使用em的这个元素的font-size。
1.em: 相对自己的font-size。自己的font-size是20px,width是10em的话,那么width就是200px。
2.如果自己没有font-size,那么继承父亲的font-size,自己的值和父亲的一样。 那么width的10em就是自己的font-size×10
3.如果自己的font-size中写有em,比如1em,那么可以理解成先继承了父亲的font-size,然后自己的值设置是继承自父元素的值的1倍,然后层叠掉了从父亲继承的值,width的10em,就是自己层叠后的值×10
比如
.father {
font-size: 30px;
}
.son {
font-size: 2em;
width: 10em;
height: 10em;
background-color: red;
}
这个时候son的font-size就是60,高和宽是600px。在son里面写了宽是10em,那么这个em就是先对于son这个div的font-size。都是相对于自己的。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.container {
font-size: 15px;
}
.box {
/* font-size: 20px; */
/* 如果自己没有设置, 那么会继承父元素的font-size */
/*
如果font-size中有写em单位, 可以理解成相对于父元素
但是更准确的理解依然是相对于自己的
*/
font-size: 2em;/* 15*20 = 30 */
/* 1.em: 相对自己的font-size。自己的font-size是20px,width是10em的话,那么width就是200px。
2.如果自己没有font-size,那么继承父亲的font-size,自己的值和父亲的一样。 那么width的10em就是自己的font-size*10
3.如果自己的font-size中写有em,比如1em,那么可以理解成先继承了父亲的font-size,然后自己的值设置是继承自父元素的值的1倍,然后层叠掉了从父亲继承的值,width的10em,就是自己层叠后的值*10
*/
width: 10em;/* 30*10 = 300 */
height: 5em;/* 30*5 = 150 */
background-color: orange;
}
</style>
</head>
<body>
<div class="container">
<div class="box">我是box</div>
</div>
</body>
</html>
![](https://img.haomeiwen.com/i27388007/f7e45e707d704556.png)
![](https://img.haomeiwen.com/i27388007/e1edd883c1eea659.png)
2.2.rem
![](https://img.haomeiwen.com/i27388007/7211945ae3efaf9a.png)
rem是相对于html的font-size。em是相对于自身的font-size。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
html {
font-size: 1.5px;
}
.box {
width: 100rem;/* 1.5*100=150 */
height: 100rem;/* 1.5*100=150 */
font-size: 20rem;/* 1.5*20=30 */
background-color: orange;
}
</style>
</head>
<body>
<div class="box">
我是box
</div>
</body>
</html>
![](https://img.haomeiwen.com/i27388007/6e6a005d45c9d793.png)
![](https://img.haomeiwen.com/i27388007/6fb15e228f014157.png)
:root{}也是html
2.3. vw/vh
vw 视窗宽度的1%
vh 视窗高度的1%
.box {
width: 10vw;/* viewport width 视口宽度的百分之10*/
height: 10vh;/* viewport height 视口宽度的百分之10*/
background-color: orange;
}
网友评论