Is there a way to have a child DIV within a parent container DIV that is wider than its parent. The child DIV needs to be the same width as the browser viewport.
See example below:
The child DIV must stay as a child of the parent div. I know I can set arbitrary negative margins on the child div to make it wider but I can't work out how to essentially make it 100% width of the browser.
I know I can do this:
.child-div{
margin-left: -100px;
margin-right: -100px;
}
But I need the child to be the same width as the browser which is dynamic.
Thanks for your answers, it seems the closest answer so far is to make the child DIV position: absolute
, and set the left and right properties to 0.
The next problem I have is that the parent has position: relative
, which means that left and right properties are still relative to the parent div and not the browser, see example here: jsfiddle.net/v2Tja/2
I can't remove the position: relative
from the parent without screwing everything else up.
In this case, we set the child element's width to be 100% of the viewport width by using a percentage viewport unit (vw), then, we move it to the left side (by the distance of the viewport's half, minus 50% of the width of the parent element) with the left property.
You can simply use the CSS display property with the value inline-block to make a <div> not larger than its contents (i.e. only expand to as wide as its contents).
Its width will be worked out based on the pixel width of its content and will be calculated after the contents are rendered. So at the point, IE encounters and renders your relatively positioned div its parent has a width of 0 hence why it itself collapses to 0.
.child {
width: 100vw;
position: relative;
left: calc(-50vw + 50%);
}
We set the width
of the child element to fill the entire viewport width, then we make it meet the edge of the screen by moving it to the left
by a distance of half the viewport, minus 50% of the parent element's width.
Demo:
* {
box-sizing: border-box;
}
body {
margin: 0;
overflow-x: hidden;
}
.parent {
max-width: 400px;
margin: 0 auto;
padding: 1rem;
position: relative;
background-color: darkgrey;
}
.child {
width: 100vw;
position: relative;
left: calc(-50vw + 50%);
height: 100px;
border: 3px solid red;
background-color: lightgrey;
}
<div class="parent">
Pre
<div class="child">Child</div>
Post
</div>
Browser support for vw and for calc() can generally be seen as IE9 and newer.
Note: This assumes the box model is set to border-box
. Without border-box
, you would also have to subtract paddings and borders, making this solution a mess.
Note: It is encouraged to hide horizontal overflow of your scrolling container, as certain browsers may choose to display a horizontal scrollbar despite there being no overflow.
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