CSS元素沿底对齐技巧在网页设计中,我们经常会遇到一些需要将元素沿底部对齐的场景,比如在一个div容器中,有两个子元素,一个高度较大,一个高度较小,我们希望这两个子元素的底部都在同一水平线上,这时候我...
CSS元素沿底对齐技巧
在网页设计中,我们经常会遇到一些需要将元素沿底部对齐的场景,比如在一个div容器中,有两个子元素,一个高度较大,一个高度较小,我们希望这两个子元素的底部都在同一水平线上,这时候我们就需要一些技巧来实现。
使用CSS的flex
CSS的flex布局是目前常用的一种布局方式,通过设置容器display:flex属性,我们可以很方便地实现子元素的对齐问题。具体地,我们可以设置子元素的align-self属性为flex-end,就可以实现子元素沿底对齐的效果。
代码如下:
<div class="container">
<div class="child1">高度较大元素</div>
<div class="child2">高度较小元素</div>
</div>
<style>
.container{
display:flex;
flex-direction:column;
justify-content:flex-end;
}
.child1{
height:200px;
background-color:red;
}
.child2{
height:50px;
background-color:green;
align-self:flex-end;
}
</style> <div class="container">
<div class="child1">高度较大元素</div>
<div class="child2">高度较小元素</div>
</div>
<style>
.container{
position:relative;
height:300px;
}
.child1{
height:200px;
background-color:red;
}
.child2{
height:50px;
background-color:green;
position:absolute;
bottom:0;
}
</style>