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?
Position fixed 100 of parent
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.
@AmrNoman Bad?? .. that was nicely put :) .. but looking forward when we can use it cross browser –
Chafer
Set transform: translate3d(0, 0, 0);
to the parent.
Just a bit of friendly advice, a full code block would severely improve the quality of your answer. i.e.
.container { -webkit-transform: translate3d(0, 0, 0); -o-transform: translate3d(0, 0, 0); transform: translate3d(0, 0, 0); }
(obviously formatted properly) and an explanation of why you say that it works would be bonus points :) –
Gasparo © 2022 - 2024 — McMap. All rights reserved.
.container
were inside a.super-container
with awidth
different than100%
. – Pricecutting