How can I set a fixed position div to inherit the width of the parent?

Is there a way that a fixed positional div can inherit the width of the parent?

I know that the fixed width is relative to the window, so this code does not work:

#wrapper{ position: relative; width:500px; height: 20px; background-color: blue; } #header{ position: fixed; width: 100%; height: 20px; background-color: rgba(255,0,0,0.5); } 
 <div id="wrapper"> #wrapper <div id="header"> #header </div> </div> 
+6
source share
2 answers

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; /* for demo */ } #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> 
+9
source

Edit

 #wrapper{ position: relative; width:500px; } 

to

 #wrapper{ position: absolute; width:500px; } 
0
source

Source: https://habr.com/ru/post/981103/


All Articles