表达百分比高度的更好方式

February 10, 2026

2026 年 2 月 10 日

Percentage height is a common issue in CSS. Using height: 100% to fill the vertical space fails in most cases because the parent container doesn't have an explicit height. Even if the parent has a definite height, you may still face issues related to margin, box-sizing, etc.

CSS 中的百分比高度是一个常见问题。使用 height: 100% 来填充垂直空间在大多数情况下会失败,因为父容器没有明确的 height。即使父级有确定的高度,你仍然可能面临与 margin、box-sizing 等相关的问题。

Instead of height: 100%, you can rely on the new stretch value that will do a better job!

代替 height: 100%,你可以依赖新的 stretch 值,它会做得更好!

.box { height: stretch;}

How does it work? #

它是如何工作的? #

As its name suggests, it will try to stretch the element to fill the parent container (more precisely the containing block).

正如其名所示,它会尝试拉伸元素以填充父容器(更精确地说是包含块)。

It works following two rules:

它遵循两条规则工作:

  1. If the element can be aligned using align-self (and align-items), the value produces the same result as a stretch alignment (align-self: stretch).
  2. 如果元素可以使用 align-self(和 align-items)进行对齐,则该值产生与拉伸对齐相同的结果(align-self: stretch)。
  3. If alignment doesn't apply, it works the same way as height: 100%, expect that margin is considered and the value of box-sizing doesn't matter. In other words, you won't get overflow issues due to margin, padding, or border.
  4. 如果对齐不适用,它的工作方式与 height: 100% 相同,除了会考虑 margin,并且 box-sizing 的值无关紧要。换句话说,你不会因为 margin、padding 或 border 而出现溢出问题。

In the demo below, height: 100% will either fail or create an overflow, while height: stretch is perfect!

下面的演示中,height: 100% 要么失败要么造成溢出,而 height: stretch 则完美!

⚠️ Limited Support (Chrome-only for now)

⚠️ 有限支持(目前仅 Chrome)

Additionally, using height: stretch gives the element a definite height, allowing for a cascading stretch.

此外,使用 height: stretch 为元素提供确定的高度,从而允许级联拉伸。

* { height: stretch;}

stretch may not work if self-alignment doesn't apply to the element AND the parent container (containing block) doesn't have an explicit height. Similar to height: 100%, it will fallback to auto. Those cases are rare, but don't forget about them.

stretch 如果自对齐不适用于元素并且父容器(包含块)没有明确的高度,则...

开通本站会员,查看完整译文。

inicio - Wiki
Copyright © 2011-2026 iteam. Current version is 2.153.0. UTC+08:00, 2026-02-16 06:05
浙ICP备14020137号-1 $mapa de visitantes$