How can I force an outer div to expand to height of inner div?

梦想的初衷 提交于 2019-12-07 18:08:24

问题


I have data that is ajaxed in to <div class="content">. I want the outer div to expand to the height of the inner div. I can't figure out how to do this.

HTML:

<div class="outer">
    <div class="inner">
        <div class="content">Stuff goes here</div>
    </div>
</div>

CSS:

.outer {
    width: 740px;
    min-height: 250px;
    margin: 0 auto;
    position: relative;
    margin-bottom: 10px;
}

.inner {
    position: absolute;
    top: 70px;
    left: 10px;
    width: 335px;
    bottom: 0;
}

.content {
    font-size: 13px;
    margin: 0 0 7px 0;
    text-align: left;
    position: relative;
}

I want the outer div to expand to the height of whatever is inside <div class="content"></div>. How can I do this?


回答1:


This happens when you use POSITION in your CSS. Remove the POSITION from the INNER class and the OUTER div will expand correctly. Perhaps you could use margins to position you inner div.

EDIT:

Here is a possible alternate CSS for you. It may or may not be appropriate for you requirements.

.outer {
    width: 740px;
    min-height: 250px;
    margin: 0 auto;
    position: relative;
    padding-top:70px;
    padding-left:10px;
    margin-bottom: 10px;
}

.inner {
    width: 335px;
    bottom: 0;
}

.content {
    font-size: 13px;
    margin: 0 0 7px 0;
    text-align: left;
    position: relative;
}



回答2:


The position:absolute in the inner div is the main problem. Here is an example with positions removed, note you need to add the nbsp; to the outer div to show.

<!doctype html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style>

.outer {
    width: 740px;
    margin: 0 auto 10px auto;
    background:#F90;
}

.inner {
    margin:70px 0 0 10px;
    width: 335px;
    bottom: 0;
    background:#9FF;
}

.content {
    display:block;
    font-size: 13px;
    margin: 0 0 7px 0;
    text-align: left;
    background:#CCC;
}
</style>
</head>

<body>
    <div class="outer">&nbsp;
        <div class="inner">
            <div class="content">Stuff goes here. </div>
        </div>
    </div>
</body>
</html>



回答3:


You could use javascript to resize the outer div. Put this into the callback of your AJAX request:

    var $inner = $('.inner');
    var height = parseInt($inner.height()) + parseInt($inner.css('top'));  
    $('.outer').css('height', height);  

Assuming that you use jQuery, that is...



来源:https://stackoverflow.com/questions/13522093/how-can-i-force-an-outer-div-to-expand-to-height-of-inner-div

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!