In CSS, when we use percentages to specify sizes or positions are calculated based on the containing block of the element. By default (and in most cases), it is the element's parent element. It may change based on a few factors:
- For boxes with position: static, relative, static, the containing block is formed by the content edge of the nearest block container ancestor box.
- For boxes with position : absolute, the containing block is formed by the edge of the padding box of the nearest ancestor element that has a position value other than static (fixed, absolute, relative, or sticky)
- If the element has 'position: fixed', the containing block is established by the viewport
Watch out for
Percentage base: Percentage values are calculated based on containing block, NOT the element.
Margin, padding (horizontal & vertical) percentages are wrt width of containing block.
Top,bottom properties compute percentage values from the height of the containing block; left, right properties compute percentage values from the height of the containing block
-
For absolute or fixed positioned elements, the containing block may also be formed by the nearest ancestor element that has the following:
- A transform or perspective value other than none
- A will-change value of transform or perspective
- A filter value other than none or a will-change value of filter (only works on Firefox)
- A contain value of paint (e.g. contain: paint;)
In this cases, the containing block is formed by the edge of the padding box.
Top comments (0)