2015-09-05 88 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>

相关问题