【问题标题】:How can I force an outer div to expand to height of inner div?如何强制外部 div 扩展到内部 div 的高度?
【发布时间】:2017-01-11 01:46:15
【问题描述】:

我有 ajaxed 到 <div class="content"> 的数据。我希望外部 div 扩展到内部 div 的高度。我不知道该怎么做。

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

我希望外部 div 扩展到 &lt;div class="content"&gt;&lt;/div&gt; 内部的高度。我该怎么做?

【问题讨论】:

  • 我没有使用过 javascript,因为我认为有一种方法可以通过仅使用 CSS 来实现。

标签: css height


【解决方案1】:

当您在 CSS 中使用 POSITION 时会发生这种情况。从 INNER 类中删除 POSITION 并且 OUTER div 将正确展开。也许您可以使用边距来定位您的内部 div。

编辑:

这是一个可能的替代 CSS 供您使用。它可能适合也可能不适合您的要求。

.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;
}

【讨论】:

  • 你。我已经和这个斗争了半个小时了。我已经在内部 div 上设置了位置。再也不会了。
【解决方案2】:

内部 div 中的 position:absolute 是主要问题。这是一个删除位置的示例,注意您需要添加 nbsp;到要显示的外部 div。

<!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】:

    您可以使用 javascript 来调整外部 div 的大小。将此放入您的 AJAX 请求的回调中:

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

    假设你使用的是jQuery,那就是……

    【讨论】:

    • 对 javascript 的建议不屑一顾……蹩脚
    • 为我工作!非常感谢!!!但是请解释一下这里的代码,第2行比较混乱
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-22
    相关资源
    最近更新 更多