Skip to content Skip to sidebar Skip to footer

Why Does Percentage Height Work On Position Fixed Element?

I've learned that percentage height only works if the parent (and parents) elements all has height value set. But why that is not required on a position:fixed element.

Solution 1:

position: fixed is relative to the screen's viewport and ignores parent elements' positioning.

https://developer.mozilla.org/en-US/docs/Web/CSS/position

fixed

Do not leave space for the element. Instead, position it at a specified position relative to the screen's viewport and don't move it when scrolled. When printing, position it at that fixed position on every page.

Solution 2:

Usually, height percentages don't work if the parent has the initial height: auto.

That's because height percentages are resolved with respect to the height of the containing block. But if the block ancestor which establishes the containing block has height: auto, its height will be the height of its contents.

That would be a circular definition, so the percentage is treated as auto.

However, this problem is avoided with absolute positioning (including fixed one). Absolutely positioned elements are taken out-of-flow, so they have no impact on the height of block ancestors with height: auto. In that case it's no longer a circular definition, so it works.

This is explained in the spec:

The percentage is calculated with respect to the height of the generated box's containing block. If the height of the containing block is not specified explicitly (i.e., it depends on content height), and this element is not absolutely positioned, the value computes to 'auto'.

Post a Comment for "Why Does Percentage Height Work On Position Fixed Element?"