如何在添加更多子级 DIV 时使父级/容器 DIV 增长。
<div id="container">
<div id="child" style="height:100px;">
</div>
<div id="child2" style="height:100px;">
</div>
</div>
父级 div 不随内容而增高的唯一原因是其内容绝对定位或使用浮动,如果是前者,则除了使用 JavaScript 调整大小外,没有其他办法。如果是后者,您可以在浮动元素末尾放置以下代码:
<br style="clear: both">
所以假设你的示例中两个子元素都有浮动属性,代码会像这样
<div id="container">
<div id="child" style="height:100px;">
** CONTENT GOES HERE **
<br style="clear: both">
</div>
<div id="child2" style="height:100px;">
** CONTENT GOES HERE **
<br style="clear: both">
</div>
</div>
你可以使用任何节点,只要在其上使用 "clear: both" (所以 <div style="clear: both"></div>
也可以使用)。
#container
样式中添加 overflow: hidden
,而不是使用 <br>
。 - BoltClockoverflow:hidden
的作用是因为许多 DOM 元素会完全忽略高度设置,除非明确指示这样做。使用 overflow:hidden
只对浮动的子元素有效。 - Michael Irigoyen如果你的 <div>
里面的内容被浮动了,那它将不会自动扩展高度。你可以通过在父级 <div>
上添加 overflow:hidden
的CSS样式来解决这个问题。需要注意的是,如果子元素都被绝对定位了,这种方法是不起作用的。当你给一个元素设置绝对定位时,它会脱离文档流。在定位方面,该元素不再是“子元素”,尽管从语义上说它仍然是。
<div style="overflow:hidden">
<div style="float:left">
<!--Content-->
</div>
<div style="float:left">
<!--Content-->
</div>
</div>
在父级div中使用display:table可以使其即使内容是浮动元素也能扩展。它基本上让div表现得像一个表格。
display: unset;
或display: inline;
可以在父元素上起作用。
.clearfix{clear:both;}
那么,当你需要的时候,你总是可以使用它。
<div class='wrapperContainer'>
<div class="classFloated">
Content
</div>
<div class="clearfix"></div>
<div class="classFloated">
Content
</div>
<div class="clearfix"></div>
</div>
将 display:flex 添加到父 div 可能起作用。
例如,我想要一排未知数量的圆圈,在一个绝对定位的 div 中居中,随着添加更多圆圈而扩展。
#grandparent{
width:300px;
height:20px;
position:absolute;
right:30;
bottom:30;
}
#parent{
transform: translateX(-50%);
left: 50%;
position: absolute;
display: flex;
}
.children{
background-color: white;
border-radius: 50%;
width: 16px;
height: 16px;
margin-left: 3px;
margin-right: 3px;
}
#container
有哪些样式? - BoltClock