Kevin Wheeler Kevin Wheeler - 6 months ago 9
CSS Question

CSS height set to percent, is it relative to the parents content box, or padding box, etc

MDN says:

The percentage is calculated with respect to the height of the generated box's containing block.


So we have a containing block that contains a child element. The child element has
height: 100%
or some other percent.

If the containing block has height, padding, and border set, is the child elements height calculated as 100% of the containing block's content-box height, padding-box height, border-box height?

If we change the box-sizing of the container block, but also make other changes such that the container block's content-box/padding-box/border-box sizes do not change, is the size of the child element affected?

EDIT: apparently padding-box is experimental and only supported by FF.

Answer

The % based size of the child is indeed calculated with respect to the size of the parent, and it does take into account box-sizing.

See this demo:

.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;
}
<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>