Set height of a div whose children are position: absolute
I have following HTML+CSS markup:
<div id="protofade" style="position: relative;">
<div style="position: absolute;"><img src="slide-01.jpg"></div>
<div style="position: absolute;"><img src="slide-02.jpg"></div>
<div style="position: absolute;"><img src="slide-03.jpg"></div>
</div>
Notice that the slides are absolute-positioned inside a relative-positioned element so that the top-left corners of all slides are align开发者_如何学编程ed together. All slides are equal height, but the height is not pre-determined hence this problem: the "protofade" div does not have a height. Is there any CSS trick that can make this div as tall as the first slide without explicitly specifying height: NNpx
.
<div id="protofade" style="position: relative;">
<div style="position: absolute;"><div style="width: 200px; height: 50px; background: #F66;"></div></div>
<div style="position: absolute;"><div style="width: 200px; height: 50px; background: #6F6;"></div></div>
<div style="position: absolute;"><div style="width: 200px; height: 50px; background: #66F;"></div></div>
<div style="visibility:hidden;"><div style="width: 200px; height: 50px; background: red;"> This should be a second copy of slide one </div></div>
</div>
The above code shows your original code (except with divs, as per Scott Brown, above), with the addition of a second copy of "slide 1", positioned with the default algorithm, but with its box hidden. Accordingly, it's container, protofade, has to be large enough to accomomdate the box, even though the box is not displayed.
There is a jQuery answer to this. I don't believe this can be done through CSS as you need to be able to get the height of the first div.
I've illustrated it here: http://jsfiddle.net/thewebdes/FHgz5/
For reference, here's a run down of the code:
HTML
<!--
using DIVs in place of IMGs
setting height to these DIVs, all equal as specified
-->
<div id="protofade" style="position: relative;">
<div style="position: absolute;"><div style="width: 200px; height: 50px; background: #F66;"></div></div>
<div style="position: absolute;"><div style="width: 200px; height: 50px; background: #6F6;"></div></div>
<div style="position: absolute;"><div style="width: 200px; height: 50px; background: #66F;"></div></div>
</div>
CSS
/* border set to show height given to DIV */
#protofade { border: 5px solid #000; }
JS
// CSS height set based on the height of the first DIV
// First DIV chosen as all heights will be the same anyway so it shouldn't matter.
$('#protofade').css("height", $('#protofade div:eq(1)').height());
精彩评论