Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between % and vw in css?

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

like image 204
DragonKnight Avatar asked Apr 05 '15 23:04

DragonKnight


1 Answers

They aren't necessarily interchangeable.

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

A strictly percentage based width will always be relative to another element's width, but when using viewport-percentage lengths, an element's width can actually be relative to the viewport's height. For instance, if an element has a width of 100vh, it will have a width of 100% of the viewport's height. This isn't possible when using strictly percentage based widths.

Viewport-percentage length are always going to be relative to their initial containing block, which is the viewport:

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.

Whereas percentage based units are going to be relative to their parent element (i.e., their containing block), which may happen to be the body/html element, in which case they will be similar to viewport-percentage lengths.

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.

like image 127
Josh Crozier Avatar answered Oct 13 '22 21:10

Josh Crozier