This "works" fine if your parent div is the same width as the body. Of course, it is only working in appearance, not reality. This div takes 30% of the browser's width, like its parent div.
html, body {
margin: 0;
}
.container {
width: 30%;
height: 400px;
background: linear-gradient(green, white)
}
.fixed {
position: fixed;
background: red;
width: inherit;
height: 10px;
}
<div class="container">
<div class="fixed"></div>
</div>
Otherwise, to accomplish this in CSS, you have a couple options, depending on your structure.
We know based on your question that the direct parent of the fixed
div has a percentage width (we'll use 30%
). That .container
div must have one or more parent divs that have:
- A fixed width in pixels
- A width in percentage
- A width in vw, em, etc.
This will (probably) be calculated in CSS. Otherwise, I don't know why you would want a CSS-only solution.
So if you have a parent of the container div with a width of 500px
, you can make your fixed
div the same width as the .container
by giving it 30% of 500px:
html, body {
margin: 0;
}
.parent {
width: 500px;
height: 400px;
background: linear-gradient(blue, white)
}
.container {
width: 30%;
height: 400px;
background: linear-gradient(green, white)
}
.fixed {
position: fixed;
background: red;
width: calc(500px * .3);
height: 10px;
}
<div class="parent">
<div class="container">
<div class="fixed"></div>
</div>
</div>
This would also work if the .parent
div has a width in %
or vw
, or anything else:
html, body {
margin: 0;
}
.parent {
width: 50%;
height: 400px;
background: linear-gradient(blue, white)
}
.container {
width: 30%;
height: 400px;
background: linear-gradient(green, white)
}
.fixed {
position: fixed;
background: red;
width: calc(50% * .3);
height: 10px;
}
<div class="parent">
<div class="container">
<div class="fixed"></div>
</div>
</div>
Obviously, you will have to know the widths of all the parents up to either the body or the nearest div with a fixed width and do the math in the CSS calc
to adjust. But again, assuming no JS and that all parent div widths are defined in CSS, this could be done.
Edit: based on your updated question:
html, body {
margin: 0;
}
.master-container {
width: 100%;
max-width: 1200px;
margin: 0 auto;
background: linear-gradient(blue, white)
}
.container {
width: 30%;
height: 400px;
background: linear-gradient(green, white)
}
.fixed {
position: fixed;
background: red;
width: calc(1200px * .3);
height: 10px;
}
@media (max-width: 1200px) {
.fixed {
width: 30%;
}
}
<div class="master-container">
<div class="container">
<div class="fixed"></div>
</div>
</div>