簡體   English   中英

如何在子 div 周圍自動調整我的父 div?

[英]How do I automatically adjust my parent div around children divs?

對於這個問題可能引起的任何混淆,我深表歉意,我只是將腳趾浸入 html 中,任何幫助表示贊賞。

為了指定我所談論的元素,我將它們的 CSS 選擇器放在括號內以試圖消除混淆。 出於某種原因,我的父 div #box_one div{}正在根據其子 div 的高度進行調整,而不是根據其寬度進行調整。

例如,子 div 的#box_one div{} > div高度是100px ,因此它的父級調整到該高度,加上額外的填充。 但是,當我將子 div 的#box_one div > div寬度更改為20px ,父 div #box_one div{}保持不變,其寬度#box_one最外層的父級#box_one

 #box_one { border: 3px outset #eee; margin: 10px; width: 400px; height: 400px; background-color: #eee; padding-top: 1%; padding-bottom: 1%; padding: 10px; } #box_one div { margin-top: 20px; border: inset; padding: 5%; } #box_one div>div { height: 100px; width: 200px; margin: 0px; } p { text-align: center; border-style: inset; margin-top: 0px; }
 <html> <head> <title>Text</title> <link rel="stylesheet" type="text/css" href="website.css"> </head> <body> <div id="box_one"> <p>This is some text.</p> <div> <div></div> </div> </div> </body> </html>

默認情況下,塊元素會占用所有可用寬度,默認情況下為 0 高度。 因此,除非另有定義,否則父元素將始終為 100% 寬度,但只能與子元素一樣高。

如果您希望父寬度符合其子項的寬度,您可以指定float (如float: left; )或display: inline-block; 給父母。

 * {box-sizing:border-box;} #box_one { border: 3px outset #eee; margin: 10px; background-color: #eee; padding-top: 1%; padding-bottom: 1%; padding: 10px; float: left; } #box_one div { margin-top: 20px; border: inset; padding: 5%; } #box_one div>div { height: 100px; width: 200px; margin: 0px; } p { text-align: center; border-style: inset; margin-top: 0px; }
 <html> <head> <title>Text</title> <link rel="stylesheet" type="text/css" href="website.css"> </head> <body> <div id="box_one"> <p>This is some text.</p> <div> <div></div> </div> </div> </body> </html>

您可以將其設置為inline-block並從其 CSS 中刪除所有寬度和高度設置。 但在這種情況下,請確保孩子有內容和/或固定的寬度和高度:

 #box_one{ border:3px outset #eee; margin:10px; display: inline-block; background-color: #eee; padding-top: 1%; padding-bottom: 1%; padding:10px; } #box_one div{ margin-top:20px; border:inset; padding: 5%; } #box_one div>div{ height: 100px; width:200px; margin:0px; } p{ text-align: center; border-style:inset; margin-top:0px; }
 <head> <title>Text</title> <link rel="stylesheet" type="text/css" href="website.css"> </head> <body> <div id="box_one"> <p>This is some text.</p> <div> <div></div> </div> </div> </body>

Div 是塊元素並嘗試盡可能多地在水平方向上占用空間,因此如果未指定特定寬度,它實際上會占用其父 div 的寬度。

div 的高度由孩子的高度定義,但寬度將由其父的寬度定義。 要在其子級周圍調整 div,最好將父 div 的寬度設置為您需要的任何寬度,並將子 div 的寬度設置為 100%,將子級的高度設置為您需要的高度,或者添加您需要的內容,其高度將被兩個div采用。

div.parent {
   width: 20px;
}
div.child {
   width: 100%;
   height: 50px;
}

<div class="parent">
     <div class="child"></div>
</div>

設置在最大的子元素內:

 display: contents;

暫無
暫無

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

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