CSS中的属性值可以使用两种不同的单位:相对单位和绝对单位。今天我们主要讨论相对单位,包括百分比、em、rem和vw/vh。1. 百分比百分比是相对于父元素的大小进行计算的单位。例如,如果我们有一个宽...
CSS中的属性值可以使用两种不同的单位:相对单位和绝对单位。今天我们主要讨论相对单位,包括百分比、em、rem和vw/vh。
1. 百分比
百分比是相对于父元素的大小进行计算的单位。例如,如果我们有一个宽度为300px的父元素,我们可以将其子元素的宽度设置为50%来让其宽度等于150px。使用百分比可以在不同屏幕尺寸和设备上实现更好的响应式布局。
示例代码:
<style>
.parent {
width: 300px;
height: 300px;
background-color: lightgray;
}
.child {
width: 50%;
height: 50%;
background-color: gray;
}
</style>
<div class="parent">
<div class="child"></div>
</div> <style>
.outer {
font-size: 16px;
}
.inner {
width: 2em;
height: 2em;
background-color: gray;
}
</style>
<div class="outer">
<div class="inner"></div>
</div> <style>
html {
font-size: 16px;
}
.container {
width: 20rem;
height: 10rem;
background-color: lightgray;
}
.box {
width: 50%;
height: 50%;
background-color: gray;
}
</style>
<div class="container">
<div class="box"></div>
</div> <style>
.container {
width: 100vw;
height: 100vh;
background-color: lightgray;
}
.box {
width: 50vw;
height: 50vh;
background-color: gray;
}
</style>
<div class="container">
<div class="box"></div>
</div>