如何使子元素div扩展到父元素div的大小

6

你好,我有一个问题,想让我的子div高度和它所在的父div一样高。

以下是父div的CSS:

#wrapper #content {
    border: 1px ridge #999;
    height: auto;
    min-height: 1000px;
    width: 1100px;
    margin-top: 40px;
    margin-right: auto;
    margin-bottom: 30px;
    margin-left: auto;
    float: left;
}

以下是子div的css

.tab_container {
    clear: both;
    width: 100%;
    border-right: 1px ridge #999;
    margin-bottom: 20px;
    height: 100%;
}

有什么办法可以解决这个问题吗?

4个回答

3
你可以使用以下样式来实现:(灵感来自于这个问题:CSS - Expand float child DIV height to parent's height
#content {
    border: 1px ridge #999;
    height: auto;
    min-height: 1000px;
    width: 1100px;
    margin-top: 40px;
    margin-right: auto;
    margin-bottom: 30px;
    margin-left: auto;
    float: left;
    position: relative; /* added */
    width: 100%; /* added */
}

.tab_container {
    border: 1px ridge orange; /* added */
    clear: both;
    width: 100%;
    border-right: 1px ridge #999;
    margin-bottom: 20px;
    height: 100%;
    position: absolute; /* added */
}

Fiddle here


0

你在两个元素上都设置了 margin-bottom。由于子元素有底部边距,它的高度将始终比父元素小。移除 margin-bottom 样式可能会让它更接近。


-1

你可以使用jQuery来实现。请查看下面的示例代码。

<html>
<head>
<title>Auto Height in jQuery</title>
<script type="text/javascript" src="jquery-1.6.2.min.js"></script>
<script type="text/javascript">
$(function(){
    var height = $("#content").height();
    $(".tab_container").height(height);
});
</script>
<style type="text/css">
#wrapper #content {
    border: 1px ridge #999;
    height: auto;
    min-height: 1000px;
    width: 1100px;
    margin-top: 40px;
    margin-right: auto;
    margin-bottom: 30px;
    margin-left: auto;
    float: left;
}
.tab_container {
    clear: both;
    width: 100%;
    border-right: 1px ridge #999;
    height: 100%;
    border: 1px solid green;
}
</style>
</head>
<body>
<div id="wrapper">
    <div id="content">
        <div class="tab_container">Tab Container</div>
    </div>
</div>
</body>
</html>

1
谢谢,这个方法完美地解决了问题。不过出于某种原因,它也调整了上面的 div,我不确定为什么,但我设法调整它以适应,所以非常感谢您的帮助。 - Alistair Wise
如果您发现答案有用,可以投票支持,甚至可以通过点击正确的标记选择正确的答案。 - Thein Hla Maw

-1

父元素的高度为自动。 子元素的100%也被定义为自动,而自动会使大小适应内容。

您可以尝试给父元素添加固定高度(可能有效),或者在子元素中添加足够的内容来拉伸它;那样就会有效。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接