对于有时候我们希望在页面中让一些 div 盒子居下时,可以使用下面的三种方法: 使用 属性 使用 margin 属性 使用 flex 布局以下是每种方法的具体实现:1. 使用 属性 / 父级div...
对于有时候我们希望在页面中让一些 div 盒子居下时,可以使用下面的三种方法:
以下是每种方法的具体实现:
/* 父级div设置 position 为 relative */
.parent {
position: relative;
height: 200px;
background-color: #F0F0F0;
}
/* 子级div设置 position 为 absolute */
.child {
position: absolute;
bottom: 0;
height: 100px;
width: 100px;
background-color: #333;
color: #fff;
}
父级 div 要设置 position: relative
,使其成为子级 div 的相对定位父元素。然后子级 div 设置 position: absolute
,bottom:0
代表底部对齐,这样就能使子级 div 相对于父级 div 元素居下了。
.parent {
height: 200px;
background-color: #F0F0F0;
}
.child {
margin-top: auto;
height: 100px;
width: 100px;
background-color: #333;
color: #fff;
}
使用 margin-top: auto 可以使子级 div 元素相对于父级 div 元素居下。当设置了 margin-top: auto 时,浏览器会按照以下规则来计算
我们只需要把子级 div 的 margin-top 设置为 auto,就能使其在父级 div 中居下了。
.parent {
height: 200px;
background-color: #F0F0F0;
display: flex; /* 块级元素变为行内块级元素,且可以使用 flex 布局 */
justify-content: flex-end; /* 子元素在主轴上居于行末 */
align-items: flex-end; /* 子元素在交叉轴上居于行末 */
}
.child {
height: 100px;
width: 100px;
background-color: #333;
color: #fff;
}
使用 flex 布局时,我们只需要把父级 div 设置为 display: flex
,并且在其上设置 justify-content: flex-end
, align-items: flex-end
,就可以让子级 div 相对于父级 div 元素居下了。