Is there are way to make a child DIV's width wider than the parent DIV using CSS?
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;
}
I've searched far and wide for a solution to this problem for a long time. Ideally we want to have the child greater than the parent, but without knowing the constraints of the parent in advance.
And I finally found a brilliant generic answer here. Copying it verbatim:
The idea here is: push the container to the exact middle of the browser window with left: 50%;, then pull it back to the left edge with negative -50vw margin.
.child-div {
width: 100vw;
position: relative;
left: 50%;
right: 50%;
margin-left: -50vw;
margin-right: -50vw;
}