简体   繁体   English

为什么容器div的高度未更新?

[英]Why the container div height was not updated?

I'm adding elements into a container div whose height is 'auto' initially. 我正在将元素添加到最初高度为“自动”的容器div中。 I expect its height will be updated as the children elements appended. 我希望它的高度将随着添加的子元素而更新。 But, actually not. 但是,实际上不是。 Could someone help me? 有人可以帮我吗? I just want the container div height gets updated according to the children's height. 我只希望容器div的高度根据孩子的身高进行更新。

I used chrome debuging tool, the height of container div is less than height of children divs. 我使用了chrome调试工具,容器div的高度小于子div的高度。 Children divs are float:left . 儿童div是float:left

If you're adding floated children to a div you need to have overflow:auto; 如果要将浮动子级添加到div中,则需要overflow:auto; on the parent. 在父母身上。

You can also use another element to clear the float clear:both will do this. 您还可以使用另一个元素来清除float clear:both将执行此操作。

This is because floated elements are taken out of the document flow. 这是因为浮动元素已从文档流中删除。

Here's an example that shows you a few techniques you can use : http://jsfiddle.net/Tn5c3/ 这是一个示例,向您展示可以使用的一些技巧: http : //jsfiddle.net/Tn5c3/

The CSS CSS

#a, #b {
    padding: 10px;
    margin:10xp
}

#a {
    background: #aa0000;
}
#b {
    background: #00aa00;
    overflow: auto;
}
p {
    background: #0000aa;
    padding: 5px;
}

.clear {
    clear:both;
    height: 50px;
}

The JS JS

$('#bb').click(function() {
    addChild($('#b')); 
});

$('#ba').click(function() {
    addChild($('#a')); 
});


function addChild(parent) {
    var child = $('<p>floated para</p>').css({
        'float': 'left'
    });
    parent.append(child);
}

The HTML HTML

<button id='ba'>Add to A</button>
<button id='bb'>Add to B</button>


<div id='a'></div>
<div class='clear'></div>
<div id='b'></div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM