我有一个父级和两个孩子divs。第二个儿童div是可变的高度,但绝对位于父级的底部。
我希望第一个Div具有基于第二个Div的动态高度。我以为margin-bottom: 10px
将指定第一个Div的高度,直到第二个Div的10px上升,但显然这是不正确的。
有什么能够得到我想要的吗?
html:
<div class="parent">
<div class="first">
Hello
</div>
<div class="second" >
</div>
</div>
CSS:
.parent {
height: 500px;
min-width: 500px;
position: relative;
background-color: red;
}
.first {
background-color: green;
margin-bottom: 10px;
}
.second {
height: 100px;
background-color: grey;
bottom: 0px;
box-sizing: border-box;
position: absolute;
width: 100%;
}
jsfiddle:https://jsfiddle.net/4tjqsron/2/
边距底部只是告诉浏览器"不要让我底部的10px内的任何东西"。
我认为这可能是使用calc()
CSS功能的绝佳机会!
尝试以下操作:
.first {
background-color: green;
height: calc(100% - 110px);
}
这应该在您的第一个和第二个子元素之间留下10px空间。基本上,它告诉浏览器,第一个元素是占用其父母减110px的100%。请参阅此信息,以获取有关calc((函数的更多信息。https://www.w3schools.com/cssref/func_calc.asp我希望这会有所帮助!
编辑:我只是想到,只有当您的身高设置在其他地方时,这才有效。您可能需要根据当前的父高度设置来调整对100%参数的使用。即使是这种情况,calc((函数仍然应该被证明有用。
我没有很清楚地明确地说明了您的意思,这是我的解决方案div.second
始终垂直在div.parent
的底部对齐:
.parent {
height: 500px;
min-width: 500px;
position: relative;
background-color: red;
}
.first {
background-color: green;
margin-bottom: 10px;
}
.second {
/* height: 100px;
background-color: grey;
bottom: 0px;
box-sizing: border-box;
position: absolute;
width: 100%; */
max-height: 100%;
position: absolute;
top: auto;
bottom: 0;
}
<div class="parent">
<div class="first">
Hello
</div>
<div class="second" >No matter how many content in this div, it will always lie on the bottom of the parent div</div>
</div>