parent 中的底部垂直对齐 div
Bottom vertical align div in parent
我在垂直对齐其 parent 内的按钮时遇到问题。
该按钮应与 "info" div 的底部对齐,但我无法将其固定。
在这种情况下我无法使用 "position: absolute"。
而且我事先不知道主要parent div的高度。
HTML:
<div class="container">
<a href="#"><img src="http://placekitten.com/g/200/400" alt="" /></a>
<div class="info">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Doloribus rem tenetur temporibus voluptas repellendus.</p>
<button>Button</button>
</div>
</div>
CSS:
* { box-sizing: border-box; }
.container {
width: 200px;
height: 700px; /* The height is variable!!! */
background: #ccc;
padding: 1em;
overflow: hidden;
}
a { display: block; height: 50%; }
a img { display: block; width: 100%; max-width: 100%; }
.info {
background: #fa0;
display: block;
height: calc(50% - 1em);
margin-top: 1em;
text-align: center;
}
.info p {
display: inline-block;
width: 100%;
vertical-align: top;
background: #a0f;
margin: 0;
}
.info button {
display: inline-block;
vertical-align: bottom;
}
正如一些评论中提到的,position: absolute 是最简单的方法。但是,您说您在这个因素上受到限制,所以这里有一个使用 flexbox 的替代方案!
您需要查看父元素的三个属性:display、flex-direction 和 justify-content。然后在子元素上放置一个边距以确保其在底部居中。这是更新后的 fiddle。不需要绝对位置:) https://jsfiddle.net/jg8egtb1/
.info {
background: #fa0;
display: block;
height: calc(50% - 1em);
margin-top: 1em;
text-align: center;
display: flex;
flex-direction: column;
justify-content: space-between;
}
.info button {
margin: 0 auto;
}
我在垂直对齐其 parent 内的按钮时遇到问题。 该按钮应与 "info" div 的底部对齐,但我无法将其固定。
在这种情况下我无法使用 "position: absolute"。
而且我事先不知道主要parent div的高度。
HTML:
<div class="container">
<a href="#"><img src="http://placekitten.com/g/200/400" alt="" /></a>
<div class="info">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Doloribus rem tenetur temporibus voluptas repellendus.</p>
<button>Button</button>
</div>
</div>
CSS:
* { box-sizing: border-box; }
.container {
width: 200px;
height: 700px; /* The height is variable!!! */
background: #ccc;
padding: 1em;
overflow: hidden;
}
a { display: block; height: 50%; }
a img { display: block; width: 100%; max-width: 100%; }
.info {
background: #fa0;
display: block;
height: calc(50% - 1em);
margin-top: 1em;
text-align: center;
}
.info p {
display: inline-block;
width: 100%;
vertical-align: top;
background: #a0f;
margin: 0;
}
.info button {
display: inline-block;
vertical-align: bottom;
}
正如一些评论中提到的,position: absolute 是最简单的方法。但是,您说您在这个因素上受到限制,所以这里有一个使用 flexbox 的替代方案!
您需要查看父元素的三个属性:display、flex-direction 和 justify-content。然后在子元素上放置一个边距以确保其在底部居中。这是更新后的 fiddle。不需要绝对位置:) https://jsfiddle.net/jg8egtb1/
.info {
background: #fa0;
display: block;
height: calc(50% - 1em);
margin-top: 1em;
text-align: center;
display: flex;
flex-direction: column;
justify-content: space-between;
}
.info button {
margin: 0 auto;
}