css 中的 % 和 vw 有什么区别?

What is the difference between % and vw in css?

1vw = 1%,所以如果它们 100% 可以互换,为什么它们都存在?我觉得 % 取决于包装标签的大小,但 vh 始终取决于 window 大小,无论包装标签的大小如何。 谢谢,

它们不一定可以互换。

行为将主要取决于元素在 DOM 中的位置,因为这将决定元素的包含块是什么。如果一个元素的宽度为 100%,它将具有包含块 宽度 的宽度 100%。如果元素的宽度为 100vw,它将具有视口 宽度 100% 宽度(视口可能不是元素的包含元素,但视口百分比单位将始终相对于视口)。

严格基于百分比的宽度将始终相对于另一个元素的宽度,但是当使用视口百分比长度时,元素的宽度实际上可以相对于视口的高度。例如,如果一个元素的宽度为 100vh,则它的宽度将为视口的 高度 100%。这在严格使用基于百分比的宽度时是不可能的。

视口百分比长度总是相对于它们的 initial containing block,即视口:

5.1.2. Viewport-percentage lengths: the ‘vw’, ‘vh’, ‘vmin’, ‘vmax’ units

The viewport-percentage lengths are relative to the size of the initial containing block. When the height or width of the initial containing block is changed, they are scaled accordingly.

而基于百分比的单位将相对于它们的父元素(即它们的包含块),这可能恰好是 body/html 元素,在这种情况下它们将类似于视口百分比长度。

4.3. Percentages: the ‘<percentage>’ type

Percentage values are always relative to another value, for example a length. Each property that allows percentages also defines the value to which the percentage refers. The value may be that of another property for the same element, a property for an ancestor element, or a value of the formatting context (e.g., the width of a containing block). When a percentage value is set for a property of the root element and the percentage is defined as referring to the inherited value of some property, the resultant value is the percentage times the initial value of that property.