Make absolute positioned div expand parent div height
As you can see in the CSS below, I want child2 to position itself before child1. This is because the site I'm currently developing should also work on mobile devices, on which the child2 should be at the bottom, as it contains the navigation which I want below the content on the mobile devices. - Why not 2 masterpages? This is the only 2 divs which are repositioned in the entire HTML, so 2 masterpages for this minor change is an overkill.
HTML:
<div id="parent">
<div class="child1"></div>
<div class="child2"></div>
</div>
CSS:
parent { position: relative; width: 100%; }
child1 { width: auto; margin-left: 160px; }
child2 { width: 145px; position: absolute; top: 0px; bottom: 0px; }
child2 has dynamic height, as different subsites could have more or less navigation items.
I know that absolute positioned elements are removed from the flow, thus ignored by other elements.
I tried setting overflow:hidden;
on the parent div, but that didn't help, neither does the clearfix.
My last resort will be javascript to reposition the two divs accordingly, but for now I'll try and see if there exist a non-javascript way of doing this.
You answered the question by yourself: "I know that absolute positioned elements are removed from the flow, thus ignored by other elements." So you can't set the parents height according to an absolutely positioned element.
You either use fixed heights or you need to involve JS.
Although stretching to elements with position: absolute
is not possible, there are often solutions where you can avoid the absolute positioning while obtaining the same effect. Look at this fiddle that solves the problem in your particular case http://jsfiddle.net/gS9q7/
The trick is to reverse element order by floating both elements, the first to the right, the second to the left, so the second appears first.
.child1 {
width: calc(100% - 160px);
float: right;
}
.child2 {
width: 145px;
float: left;
}
Finally, add a clearfix to the parent and you're done (see the fiddle for the complete solution).
Generally, as long as the element with absolute position is positioned at the top of the parent element, chances are good that you find a workaround by floating the element.
Feela is right but you can get a parent div
contracting/expanding to a child element if you reverse your div
positioning. Set the parent div to position: absolute;
and position it in the browser using the left
, top
and margin
attributes as you like it. Then set the child2
to position: relative;
and set overflow
attribute to hidden
in case you want to pad or move it around using left
and top
inside the parent div
, set height: 100%;
and width: 100%
and that should work for you.
上一篇: 带有绝对定位元素的Clearfix
下一篇: 使绝对定位div扩大父div高度