问题
I have something like this:
<body>
<div style="width:700px; margin:0 auto;">
<div class="inner-div"></div>
</div>
</body>
Is there a way to expand child div with class "inner-div", to 100% of body width?
回答1:
This makes inner-div
stretch from left to right:
div.inner-div {
position: absolute;
left: 0;
width: 100%;
}
回答2:
I have not tested this but it might work:
You need jQuery for this.
//I'm using a resize event in case the body with changes. At least i think that will work.
window.onresize = function(event) {
var bWidth = $("body").width():
$(".inner-div").width(bWidth);
}
回答3:
Not with css only. Since you set a with of 700px for the parent the child inherits this. But you can do this with javascript. Here with jquery:
$(window).bind("load resize", function(){
$('.inner-div').width($('body').width());
});
It works even if you resize the window.
回答4:
Let me correct this a little bit.
You also need to give your stretching element some "min-width" value in pixels/em and (not necessary but good practice) give the body element a min-width, too.
i.e.:
body {
min-width: 1000px;
}
.outer {
width: 1000px;
height: 200px;
margin: auto;
}
.inner {
position: absolute;
min-width: 1000px;
height: 100px;
left: 0;
right: 0;
}
If there is no min-width set and your HTML/CSS isn't built for a responsive site you can see an error at the inner DIV element when resizing the browser window. The property "width: 100%" makes the element stretch always to 100% browser window size. Therefore if the browser viewport gets smaller than the content and scrollbars appear, the inner DIV stays at the actual browser viewport size causing the appearance seems broken when you scroll the site.
You can try it here: http://jsfiddle.net/W4vum/
Try changing the "min-width" value at the ".inner" DIV in the example from 1000px to 100%, resize the window and scroll to the side, then you see it.
回答5:
This is an old post but I found a better solution here: How can I expand a child div to 100% screen width if the container div is smaller?
So in this case it would be
.inner-div {
width: 100vw;
margin-left: calc(-50vw + 50%);
}
回答6:
If you give width 100% to inner-div, it will fit the width of the outer div.
回答7:
A little example of how to do it with css, so it is the same in javascript with setting the attributes I guess : http://jsfiddle.net/u8mJW/.
回答8:
To make this work in pure CSS all parent elements have to be position:static;
(or without the position attribute, because static is default)
after that you can use Stefan's code
div.inner-div {
position: absolute;
left: 0;
width: 100%;
}
(corrected Ricola3D's Fiddle: http://jsfiddle.net/u8mJW/23/ )
来源:https://stackoverflow.com/questions/11472110/how-to-expand-child-div-with-100-of-body-width