I'm in difficulty: I have a parent element that has a size that doesn't know. And I have an item that it must place permanently at the top of the body, then position: fixed
, but I cann't because giving it width: 100%
, is 100% of the body, but I want 100% of the parent element. How can I do?
Example: http://codepen.io/michele96/pen/jWbYQb
set .fixed
's width as width: inherit;
don't 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>
The problem is that, unlike absolutely positioned elements, the containing block of a fixedly positioned element is usually the viewport, not its nearest positioned element. Then, width: 100%
is resolved with respect to the viewport width.
There are ways to change this behavior, e.g. elements with transform
establish a containing block for their fixedly positioned descendants. But then your element won't be fixed 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>
Note it's not widely supported yet.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With