px
像素,假设你的屏幕分辨率是100*100,那么你设置的 width=“40px”,则是设置了宽度占40个像素
rem
rem中的 r 的单词是 root,标示根节点,在网页中,html是根节点,所以由此可以得知,rem的单位是根据html的font size属性来决定的
案例:
1、如果我们把 html 的 font-size 属性设置为16px,设置里面的元素的宽高分别为2rem、3rem、4rem,可以从最后的效果上验证上述总结
代码:
<!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>
html {
font-size: 16px;
}
.div1 {
width: 2rem;
height: 2rem;
background: red;
margin-bottom: 20px;
}
.div2 {
width: 3rem;
height: 3rem;
background: pink;
margin-bottom: 20px;
}
.div3 {
width: 4rem;
height: 4rem;
background: blue;
}
</style>
</head>
<body>
<div class="div1">div1</div>
<div class="div2">div2</div>
<div class="div3">div3</div>
</body>
</html>
效果:
em
em 和 rem 的区别是,em的值是取决于父元素或者当前元素有没有设置 font-size 属性,当前元素的 fong-size 的优先级高于父元素。
代码:
<!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>
.div1 {
font-size: 16px;
width: 2em;
height: 2em;
background: red;
margin-bottom: 20px;
}
.div2 {
font-size: 20px;
width: 4em;
height: 4em;
background: pink;
margin-bottom: 20px;
}
.div_2 {
width: 2em;
height: 2em;
color: #ffffff;
background: blue;
}
</style>
</head>
<body>
<div class="div1">div1</div>
<div class="div2">
div2
<div class="div_2">div2.2</div>
</div>
</body>
</html>
效果:
vw
可视窗口的宽度的 百分比,与直接给元素设置高度100%的区别是,不需要给根节点设置宽高为 100%;
vh
可视窗口的高度的 百分比,与直接给元素设置高度100%的区别是,不需要给根节点设置宽高为 100%;