2015-09-05 77 views
-1

我有一個包含子div的父級div。我希望父div自動調整大小,以便孩子總是在父母的邊界內。現在由於相對定位,子div的底部延伸到父代的底部。我如何獲得父級調整大小?如何獲得父級div來調整其高度

#parentDiv { 
 
    margin: 40px 0 0 40px; 
 
    background-color: #eae; 
 
    width: 1500px; 
 
    height: auto; 
 
} 
 
#childDiv { 
 
    position: relative; 
 
    max-width: 400px; 
 
    min-height: 200px; 
 
    background-color: #B9D7D9; 
 
    top: 20px; 
 
    left: 20px; 
 
}
<div id="parentDiv"> 
 
    <div id="childDiv"> 
 
    </div> 
 
</div>

回答

3

相對定位移動視覺所以,如果你想你需要移動的子元素的另一種方法在父包含它的元素。

保證金似乎是最明顯的選擇

#parentDiv { 
 
    background-color: #eae; 
 
    width: 500px; 
 
    margin: 40px; 
 
    overflow: auto; 
 
} 
 
#childDiv { 
 
    position: relative; 
 
    max-width: 400px; 
 
    min-height: 200px; 
 
    background-color: #B9D7D9; 
 
    margin-top: 20px; 
 
    margin-left: 20px;
<div id="parentDiv"> 
 
    <div id="childDiv"></div> 
 
</div>

0

擺脫了childDiv的定位。 概述了這些元素,以便您清楚地看到它們。 由於存在最小和最大尺寸,因此我將100%高度和寬度用於顯式測量。

body { 
 
    height: 100vh; 
 
    width: 100vw; 
 
} 
 
#parentDiv { 
 
    margin: 40px 0 0 40px; 
 
    background-color: #eae; 
 
    width: 1500px; 
 
    outline: 2px dashed blue; 
 
} 
 
#childDiv { 
 
    max-width: 400px; 
 
    width: 100%; 
 
    min-height: 200px; 
 
    height: 100%; 
 
    background-color: #B9D7D9; 
 
    outline: 2px solid red; 
 
}
<div id="parentDiv"> 
 
    <div id="childDiv"> 
 
    </div> 
 
</div>