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.
A more modern solution to this question is to use the viewport unit
vw
andcalc()
.Set the
width
of the child element to 100% of the viewport width, or100vw
. Then move the child element 50% of the viewport width – minus 50% of the parent element's width – to the left to make it meet the edge of the screen.Here's a demo.
Browser support for vw and for calc() can generally be seen as IE9+.
Note: This assumes the box model is set to
border-box
. Withoutborder-box
, you'll also have to subtract paddings and borders, making this solution a mess.Assuming the parent has a fixed width, e.g
#page { width: 1000px; }
and is centered#page { margin: auto; }
, you want the child to fit the width of browser viewport you could simply do: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:
Adding to Nils Kaspersson's solution, I am resolving for the width of the vertical scrollbar as well. I am using
16px
as an example, which is subtracted from the view-port width. This will avoid the horizontal scrollbar from appearing.you can try position: absolute. and give width and height , top: 'y axis from the top' and left: 'x-axis'
I had a similar issue. The content of the child element was supposed to stay in the parent element while the background had to extend the full viewport width.
I resolved this issue by making the child element
position: relative
and adding a pseudo element (:before
) to it withposition: absolute; top: 0; bottom: 0; width: 4000px; left: -1000px;
. The pseudo element stays behind the actual child as a pseudo background element. This works in all browsers (even IE8+ and Safari 6+ - don't have the possibility to test older versions).Small example fiddle: http://jsfiddle.net/vccv39j9/