简体   繁体   中英

Why the container div height was not updated?

I'm adding elements into a container div whose height is 'auto' initially. 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.

I used chrome debuging tool, the height of container div is less than height of children divs. Children divs are float:left .

If you're adding floated children to a div you need to have overflow:auto; on the parent.

You can also use another element to clear the float clear:both will do this.

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/

The 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

$('#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

<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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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