Fixed position 100 parent

I am in difficulty: I have a parent element whose size is unknown. And I have an element that it should constantly place on the top of the body, and then position: fixed , but I cannot, because I give it width: 100% , this is 100% of the body, but I want 100% of the parent element How can I do?

Example: http://codepen.io/michele96/pen/jWbYQb

+5
source share
3 answers

set .fixed width as width: inherit; do not use 100%

 body { padding: 0; margin: 0 auto; } .container { position: relative; width: 70%; height: 1000px; background: red; } .fixed { position: fixed; width: inherit; /*change here*/ line-height: 50px; background: blue; color: #f0f0f0; text-align: center; font-size: 20px; } 
 <div class="container"> <div class="fixed">Navbar Fixed</div> </div> 
+9
source

The problem is that, in contrast to absolutely positioned elements, the containing block of a motionlessly located element is usually the viewport, and not its nearest positioned element. Then width: 100% allowed relative to the width of the viewport.

There are ways to change this behavior, for example. elements with transform set the containing block for their fixed descendants. But then your item will not be pinned at the top of the viewport.

Instead, you should use sticky positioning:

 .fixed { position: sticky; top: 0; } 

 body { padding: 0; margin: 0 auto; } .container { width: 70%; height: 1000px; background: red; } .fixed { position: sticky; top: 0; line-height: 50px; background: blue; color: #f0f0f0; text-align: center; font-size: 20px; } 
 <div class="container"> <div class="fixed">Navbar Fixed</div> </div> 

Please note that it is not yet widely supported.

+6
source

Set transform: translate3d(0, 0, 0); parent element.

0
source

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


All Articles