首页 话题 小组 问答 好文 用户 我的社区 域名交易

[分享]css中如何让div盒子居下

发布于 2024-11-11 19:27:40
0
22

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

对于有时候我们希望在页面中让一些 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 元素居下了。

评论
91云脑
Lv.1普通用户

62845

帖子

12

小组

80

积分

站长交流