百分比高度相对计算

CSS 中竖向百分比值的计算基准

问题

元素竖向的百分比设定是相对于容器的高度吗?

解答

不完全是。CSS 中竖向百分比的计算基准取决于具体属性:

height 百分比

height 的百分比相对于包含块的高度

.parent {
  height: 400px;
}

.child {
  height: 50%; /* 200px,相对于父元素高度 */
}

⚠️ 注意:父元素必须有明确的高度,否则百分比高度不生效。

padding 和 margin 的竖向百分比

padding-toppadding-bottommargin-topmargin-bottom 的百分比相对于包含块的宽度(不是高度):

.parent {
  width: 400px;
  height: 200px;
}

.child {
  padding-top: 50%;    /* 200px,相对于父元素宽度 */
  margin-bottom: 25%;  /* 100px,相对于父元素宽度 */
}

完整示例

<!DOCTYPE html>
<html>
<head>
  <style>
    .container {
      width: 400px;
      height: 300px;
      background: #eee;
    }
    
    .box {
      width: 50%;          /* 200px,相对于父元素宽度 */
      height: 50%;         /* 150px,相对于父元素高度 */
      padding-top: 10%;    /* 40px,相对于父元素宽度! */
      margin-top: 10%;     /* 40px,相对于父元素宽度! */
      background: #4a90d9;
    }
  </style>
</head>
<body>
  <div class="container">
    <div class="box"></div>
  </div>
</body>
</html>

利用这个特性实现固定宽高比

由于 padding 百分比始终相对于宽度,可以用来实现响应式的固定宽高比容器:

/* 16:9 的容器 */
.aspect-ratio-box {
  width: 100%;
  padding-top: 56.25%; /* 9/16 = 0.5625 */
  position: relative;
}

.aspect-ratio-box > .content {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

关键点

  • height 百分比相对于包含块的高度
  • padding-top/bottom 百分比相对于包含块的宽度
  • margin-top/bottom 百分比相对于包含块的宽度
  • top/bottom 定位百分比相对于包含块的高度
  • 利用 padding 百分比可实现固定宽高比布局