css中如何让div盒子居下

admin 轻心小站 关注 LV.19 运营
发表于前端技术学习版块 css,教程

对于有时候我们希望在页面中让一些 div 盒子居下时,可以使用下面的三种方法: 使用 position 属性 使用 margin 属性 使用 flex 布局以下是每种方法的具体实现:1. 使用 pos

对于有时候我们希望在页面中让一些 div 盒子居下时,可以使用下面的三种方法:

  1. 使用 position 属性
  2. 使用 margin 属性
  3. 使用 flex 布局

以下是每种方法的具体实现:

1. 使用 position 属性

 /* 父级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: absolutebottom:0 代表底部对齐,这样就能使子级 div 相对于父级 div 元素居下了。

2. 使用 margin 属性

 .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 时,浏览器会按照以下规则来计算

元素的 margin-top:

  • 如果这个元素没有 margin-top,那么在上面添加一个尽量小的 margin-top
  • 如果这个元素的 margin-top 不是 auto,则保留原来的值
  • 如果 margin-top 是 auto,则根据剩余的可用空间来分配 margin-top

我们只需要把子级 div 的 margin-top 设置为 auto,就能使其在父级 div 中居下了。

3. 使用 flex 布局

 .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-endalign-items: flex-end,就可以让子级 div 相对于父级 div 元素居下了。

文章说明:

本文原创发布于探乎站长论坛,未经许可,禁止转载。

题图来自Unsplash,基于CC0协议

该文观点仅代表作者本人,探乎站长论坛平台仅提供信息存储空间服务。

评论列表 评论
发布评论

评论: css中如何让div盒子居下

粉丝

0

关注

0

收藏

0

已有0次打赏