I\'m trying to give a fixed element a width
of a percentage parent (here #container
). When I use pixel instead of the percentage then it works
There's a belief that inherited values are 'translated' from relative ones (such as percentages) into absolute ones. Guess what? It's wrong. Here's what MDN says about it:
The
inherit
CSS-value causes the element for which it is specified to take the computed value of the property from its parent element.[...]
The computation needed to reach the computed value for the property typically involves converting relative values (such as those in
em units
orpercentages
) to absolute values. For example, if an element has specified valuesfont-size: 16px
andpadding-top: 2em
, then the computed value of padding-top is32px
(double the font size).However, for some properties (those where percentages are relative to something that may require layout to determine, such as
width
,margin-right
,text-indent
, andtop
), percentage specified values turn into percentage computed values. [...] These relative values that remain in the computed value become absolute when the used value is determined.
Now an example. Let's say we have the following structure:
... and the following CSS:
#alpha { outline: 1px solid red; width: 420px; height: 100px; }
#bravo { outline: 1px solid green; width: 50%; height: inherit; margin: 0 auto; }
#charlie { outline: 1px solid navy; width: inherit; height: inherit; margin: 0 auto; }
... you'll see this picture:
... meaning that while #charlie
element has the same height as its #bravo
parent, its width is 50% of its parent. Inherited was a computed value: 100px
for height, 50%
for width.
While this feature might be good or bad, depending on situation, for non-fixed elements, it seems to be definitely hurting the fixed ones. As 50%
value for width
property is inherited as is, the used value
for that dimension will be based off the viewport. It's the same with percentage-using
values, such as calc(50%)
.