【问题标题】:Positioning a div at the bottom of a “absolute” <div>将 div 定位在“绝对”<div> 的底部
【发布时间】:2016-03-30 01:46:33
【问题描述】:
我在定位 div 时遇到问题。我想让我的child div 贴在parent div 的底部,grandchild_1 和grandchild_2 保持正确放置。我的意思是在grandchild_2 之前有grandchild_1,就像在图片上一样。
这是我尝试过的,但“子”div 粘在顶部:
#parent {
position: relative;
}
#child {
position: absolute; bottom: 0;
}
<div id="parent">
<div id="child">
<div id="grandchild_1">
</div>
<div id="grandchild_2">
</div>
</div>
</div>
有人知道我应该怎么做吗?谢谢!
【问题讨论】:
标签:
html
css
position
absolute
【解决方案1】:
如果您在父级上指定高度,它将坚持到底部。
示例:http://codepen.io/anon/pen/wGqzVd
HTML
<div id="parent">
Parent
<div id="child">
Child
<div id="grandchild_1">
Grandchild 1
</div>
<div id="grandchild_2">
Grandchild 2
</div>
</div>
</div>
CSS
div {
padding: 5px;
}
#parent {
position: relative;
background: lightgray;
height: 200px;
width: 150px;
}
#child {
position: absolute;
bottom: 5px;
background: yellow;
}
#grandchild_1 {
background: pink;
}
#grandchild_2 {
background: lightblue;
}
【解决方案2】:
提供的代码按原样工作...假设父级的高度大于子级的高度。
#parent {
position: relative;
height: 200px;
background: pink;
}
#child {
position: absolute;
width: 100%;
bottom: 0;
background: green;
}
#grandchild_1,
#grandchild_2 {
height: 25px;
background: red;
margin: 10px;
}
<div id="parent">
<div id="child">
<div id="grandchild_1">GC1
</div>
<div id="grandchild_2">GC2
</div>
</div>
</div>
作为定位的替代方法,flexbox 可以做同样的事情......并且子元素会影响父元素的高度,而绝对定位的子元素则无法。 p>
#parent {
position: relative;
height: 200px;
background: pink;
display: flex;
flex-direction: column;
justify-content: flex-end;
}
#child {
width: 100%;
background: green;
}
#grandchild_1,
#grandchild_2 {
height: 25px;
background: red;
margin: 10px;
}
<div id="parent">
<div id="child">
<div id="grandchild_1">GC1
</div>
<div id="grandchild_2">GC2
</div>
</div>
</div>