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.
source share