CSS高度设置为百分比,是相对于父内容框还是内边距框等

Kev*_*ler 3 html css

MDN说:

The percentage is calculated with respect to the height of the generated box's containing block.
Run Code Online (Sandbox Code Playgroud)

所以我们有一个包含子元素的包含块。子元素具有height: 100%或其他一些百分比。

如果包含块设置了高度、内边距和边框,则子元素高度是否按包含块的内容框高度、内边距框高度、边框框高度的 100% 计算?

如果我们更改容器块的 box-sizing,同时还进行其他更改,使容器块的 content-box/padding-box/border-box 大小不变,那么子元素的大小是否会受到影响?

编辑:显然 padding-box 是实验性的,仅受 FF 支持。

Kha*_*los 6

子级的基本尺寸%确实是根据父级的尺寸计算的,并且它确实考虑了box-sizing

看这个演示:

.box {
  width: 100px;
  height: 100px;
  
  padding: 10px;
  margin: 10px;
  border: 10px solid black;
  
  background-color: red;
  color: white;
}

.content-box {
  box-sizing: content-box;
}
.border-box {
  box-sizing: border-box;
}

.child {
  width: 100%;
  height: 100%;
  background-color: blue;
}
Run Code Online (Sandbox Code Playgroud)
<body>
  <div class="box content-box">
    <div class="child">Content Box</div>
  </div>
  
  <br/>

  <div class="box border-box">
    <div class="child">Border Box</div>
  </div>
</body>
Run Code Online (Sandbox Code Playgroud)