[英]Positioning a div at the bottom of a “absolute” <div>
I'm having troubles positioning my divs. 我在定位div时遇到了麻烦。 I want to have my child
div stick to the bottom of the parent
div, with grandchild_1
and grandchild_2
staying correctly put. 我想让我的child
div贴在parent
div的底部,并且grandchild_1
和grandchild_2
正确放置。 By that, I mean having grandchild_1
before grandchild_2
, like on the picture. 就是说,我的意思是在图片上先有grandchild_1
在grandchild_2
之前。
This is what I've tried, but the "child" div sticks to the top : 这是我尝试过的方法,但是“ child” 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>
Anyone knows how I should proceed ? 有人知道我应该如何进行吗? Thanks ! 谢谢 !
If you specify a height on the parent it will stick to the bottom. 如果您在父级上指定高度,它将保持在底部。
Example: http://codepen.io/anon/pen/wGqzVd 示例: http : //codepen.io/anon/pen/wGqzVd
<div id="parent">
Parent
<div id="child">
Child
<div id="grandchild_1">
Grandchild 1
</div>
<div id="grandchild_2">
Grandchild 2
</div>
</div>
</div>
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;
}
The provided code works as is...assuming that the parent has a height greater than that of the child. 提供的代码按原样工作...假定父母的身高大于孩子的身高。
#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>
As an alternative to positioning, flexbox can do the same... and the child will affect the height of the parent which an absolutely positioned child cannot . 作为定位的替代方法,flexbox可以执行相同的操作... 子代会影响父代的高度,而绝对定位的子代则不能 。
#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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.