开发者

Make a relative-positioned block element the same size as its contained absolute-positioned element

Ok, I'm trying to take several divs and all their content, and stack them on top of each other and make the containing div (#stack) appear in the normal flow of things via the following method:

CSS:

#stack
{
    position:relative;
    display:block;
}
#stack div
{
    position:absolute;
    left:0;
}

HTML:

<div id="stack">
    <div>
        <img src="images/1.jpg">
        <p>
            First Image
        </p>
    </div>
    <div>
        <img src="images/2.jpg">
        <p>
            Second Image
        </p>
    </div>
    <div>
        <img src="images/3.jpg">
        <p>
            Third Image
        </p>
    </div>
    <div>
        <img src="images/4.jpg">
        <p>
            Fourt开发者_开发技巧h Image
        </p>
    </div>
</div>

Which works, except now div#stack has a width/height of 0. I would like it to be the same size as its largest child.

Thanks in advance for the help!


As you are taking the inner divs out of the document's flow with position: absolute;, the outer div cannot in any case stretch to the dimensions of the biggest child. You have to use javascript to achieve that effect. If you're familiar with jQuery, you could use something like this:

var w = false, h = false;

$('#stack div').each(function() {
    w = $(this).width() > w || !w ? $(this).width() : w;
    h = $(this).height() > h || !h ? $(this).height() : h;
});

$('#stack').css({
    width: w,
    height: h
});


Setting position:absolute takes the node out of the flow, which is why the parent, not having any flowed content, gets dimensions of 0x0.

If your server code (e.g., PHP) knows about these images, you could calculate the maximum width and the maximum height among them and set the height/width of the parent appropriately.

Or, as Tatu says, you can use JavaScript and do it client-side.


Do you want the width of the #stack to shrink-wrap its children as well, or are you just concerned about its height? I'm assuming the latter, since you explicitly put display: block on it.

Because in that case, it is possible to do it just with CSS:

#stack {
    overflow: hidden;
    _zoom: 1;
}       
#stack div {
    float: left;
    margin-right: -100%;
}

I added the _zoom: 1 to trigger hasLayout in IE6. You can change that to your preferred method (e.g. in a separate IE6 stylesheet), or leave it out altogether if you don't need to support IE6.

In Opera, you can make the #stack shrink-wrap its children entirely (i.e. in width as well) when you float the stack (or display: inline-block) and add width: 100% to the child divs. I don't know if that's because of a bug in Opera, a bug in the other browsers, or just a difference due to a vague spec.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜