使div的高度随其内容扩展 [英] make div's height expand with its content
问题描述
我有这些嵌套的div,我需要主容器展开(高度)以容纳内部的DIV
I have these nested divs and I need the main container to expand (in height) to accomodate the DIVs inside
<!-- head -->
...
<!-- /head -->
<body class="main">
<div id="container">
<div id="header">
<!--series of divs in here, graphic banner etc. -->
</div>
<div id="main_content"> <!-- this DIV _should_ stretch to accomodate inner divs -->
<div id="items_list" class="items_list ui-sortable">
<div id="item_35" class="item_details">
</div>
<div id="item_36" class="item_details">
</div>
<div id="item_37" class="item_details">
</div>
<!-- this list of DIVs "item_xx" goes on for a while
each one representing a photo with name, caption etcetc -->
</div>
</div>
<br class="clear"/>
<div id="footer">
</div>
</body>
</html>
CSS是这样:
* {
padding: 0;
margin: 0;
}
.main {
font: 100% Verdana, Arial, Helvetica, sans-serif;
background: #4c5462;
margin: 0;
padding: 0;
text-align: center;
color: #000000;
}
.main #container {
height: auto;
width: 46em;
background: #4c5462;
margin: 0 auto;
border: 0px solid #000000;
text-align: left;
}
.main #main_content {
padding: 5px;
margin: 0px;
}
#items_list {
width: 400px;
float: left;
}
.items_list {
width: 400px;
float: left;
}
.item_details {
margin-top: 3px;
margin-bottom: 3px;
padding: 3px;
float: left;
border-bottom: 0.5px solid blue;
}
我遇到的问题是 #main_content
不能拉伸以适应所有的内部div,结果是它们继续背景。
The problem I have is that #main_content
doesn't stretch to accomodate all the inner divs, with the result that they keep going against the background.
我如何解决这个问题? p>
How can I solve this?
推荐答案
您需要强制清除两个
c> #main_content div已关闭。我可能会将< br class =clear/> ;;
移动到 #main_content
CSS是:
You need to force a clear:both
before the #main_content
div is closed. I would probably move the <br class="clear" />;
into the #main_content
div and set the CSS to be:
.clear { clear: both; }
更新:此问题仍然会获得大量流量,我想使用现代的替代方法更新答案,在CSS3中使用新布局模式称为弹性框 Flexbox :
Update: This question still gets a fair amount of traffic, so I wanted to update the answer with a modern alternative using a new layout mode in CSS3 called Flexible boxes or Flexbox:
body {
margin: 0;
}
.flex-container {
display: flex;
flex-direction: column;
min-height: 100vh;
}
header {
background-color: #3F51B5;
color: #fff;
}
section.content {
flex: 1;
}
footer {
background-color: #FFC107;
color: #333;
}
<div class="flex-container">
<header>
<h1>
Header
</h1>
</header>
<section class="content">
Content
</section>
<footer>
<h4>
Footer
</h4>
</footer>
</div>
目前支持 Flexbox 和视口单位,但如果您必须维护对旧版浏览器的支持,请务必检查特定浏览器版本的兼容性。
Most modern browsers currently support Flexbox and viewport units, but if you have to maintain support for older browsers, make sure to check compatibility for the specific browser version.
这篇关于使div的高度随其内容扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!