What is the difference between% and vw in css?

1vw = 1%, so if they are 100% interchangeable, why do they both exist? I feel that% depends on the size of the wrapper tag, but vh always depends on the size of the window regardless of the size of the wrapper tag. Thanks,

+6
source share
1 answer

They are not necessarily interchangeable.

The behavior will mainly depend on the position of the element in the DOM, as this will determine that the element containing the block. If an element has a width of 100% , it will have a width of 100% containing the block width . If an element has a width of 100vw , it will have a width of 100% the viewport width (the viewport may not be the element containing the element, but the units in the viewport will always be relative to the viewport).

A 100% width will always refer to a different element width, but when using the percentage of the viewport, the element width can actually be relative to the height of the viewport. For example, if an item has a width of 100vh , it will have a width of 100% the viewport height . This is not possible when using strictly percentage width.

The percentage length of the video portal will always refer to their initial containing block , which is a viewing window:

5.1.2. Percentage lengths in viewport: vw, vh, vmin, vmax units

The percentages in the viewport refer to the size of the initial containing block . When the height or width of the original containing block changes, they are scaled accordingly.

While units based on percentages will refer to their parent element (i.e. to their containing block), which may be a body / html element, in which case they will look like a percentage of the length view.

4.3. Percentage: type <percentage>

Percentage values ​​always refer to another value, for example, to length. Each property that allows percentages also defines a value that the percentage points to. The value may be the value of another property for the same element, a property for the ancestor element, or a formatting context value (for example, the width of the containing block). When a percentage value is set for a property of a root element, and a percentage is defined as referring to the inherited value of a property, the resulting value is a percentage value times the initial value of this property.

+7
source

Source: https://habr.com/ru/post/984718/


All Articles