开发者

css vertical height with position: absolute

i have this simplified skeleton structure:

<div id='parent">
    <div id="content">
        <div id="child-1"></div>
        <div id="child-2"></div>
        <div id="child-3"></div>
    </div>
</div>

I would like the parent div to expand to the height of the t开发者_JAVA技巧allest child. I can do that no problem as long as the children are not position: absolute which is what i need them to be.

When the children are set to absolute, the parent's height is no longer affected by the height of the children.

Is there a workaround for this?

Thanks


You have a couple options in this situation.

The first is to use { position: relative } instead of absolute. This keeps the elements in the flow of the page and the parent will render with the size you're looking for.

The other option is to use a bit of javascript to find the size of each child, determine which is largest, and then set the parent to that height.

var children = document.getElementById('content').getElementsByTagName('div');

var max_child_height = 0;
for(i = 0; i < children.length ; i++){
    if(children[i].offsetHeight > max_child_height) {
        max_child_height = children[i].offsetHeight;
    }
}

document.getElementById('parent').height = max_child_height;


I assume the child-N element are positioned side by side. While you do this using absolute positioning you could also do this using float:left. This way (after clearing) the parent will have the height of the highest child element.

#child-1, #child-2, #child3 {
  width: 200px;
  float: left;
}
/* now clear the float, otherwise #content would have no height*/
#content {
  overflow:hidden;/*normal browsers*/
  zoom:1;/*IE fix*/
}


You can use javascript for solving this problem. Or position:relative http://plugins.jquery.com/project/Tallest It might be useful

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜