Use the inherit value for the width property in the #header selector.
Why does it work
By pointing position: fixed to the #header element, the position of the #header element #header calculated relative to the viewport, as specified in the CSS2 specification:
http://www.w3.org/TR/2011/REC-CSS2-20110607/visuren.html#positioning-scheme
However, position: fixed does not change the structure of the DOM, which means that the #wrapper element is still the parent element of the #header element. As Therefore, #header can still inherit property values ββfrom its parent element, even if its position is determined relative to the viewport.
Please also note that if you specify a percentage value for the width, the fixed element will calculate the value based on the viewport as specified in the specification. However, this does not apply to width: inherit , which takes its value from the parent and not from the viewport.
See: http://www.w3.org/TR/2011/REC-CSS2-20110607/visudet.html#propdef-width
For example, if you added the color property to #wrapper , it would be inherited by #header .
The difference is that the initial / default value for width is auto , whereas for color it is inherit . To get the parent element with a property, you need to specify width: inherit , not width: 100% ;
Note. There is a subtle difference between the parent and the containing block. In most cases they are the same, but for fixed positioned elements they are different.
#wrapper { position: relative; width: 500px; height: 20px; background-color: blue; color: white; } #header { position: fixed; width: inherit; height: 20px; background-color: rgba(255, 0, 0, 0.5); }
<div id="wrapper"> #wrapper <div id="header"> #header </div> </div>
source share