Is there are way to make a child DIV's width wider than the parent DIV using CSS?
Is there a way to have a child DIV within a parent container DIV that is wider than it's parent. The child DIV needs to be the same width of 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.
Update
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.
Here's a generic solution that keeps the child element in the document flow:
.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.
Use absolute positioning
.child-div {
position:absolute;
left:0;
right:0;
}