簡體   English   中英

如何讓父div和它的孩子一起成長?

[英]How to make a parent div grow with its children?

當添加更多子 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>也可以)。

如果<div>的內容是浮動的,它就不會展開。 您可以通過將overflow:hidden CSS 樣式放置到父<div>來輕松解決此問題。 請注意,如果孩子都絕對定位,這將不起作用。 當您絕對定位一個元素時,您就是將它從文檔流中取出。 就定位而言,該元素不再是“孩子”,即使在語義上它仍然是。

<div style="overflow:hidden">
  <div style="float:left">
    <!--Content-->
  </div>
  <div style="float:left">
    <!--Content-->
  </div>
</div>

在父 div 中使用 display:table 使其增長,即使其內容是浮動元素。 基本上,它使 div 表現得像一張桌子。

查看顯示屬性: http : //www.w3.org/wiki/CSS/Properties/display

通常我創建一個修復類:

.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 為中心,該 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;

}

https://codepen.io/anon/pen/zXwRza

display: unset; display: inline; 適用於父元素。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM