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

[分享]css中如何让几个盒子平均分

发布于 2024-11-11 19:24:39
0
11

在CSS中,有时候需要让几个盒子平均分布在一个容器中,这是一个非常常见的需求。下面介绍几种实现方法: / 方法一:使用flexbox布局 / .container { display: flex; j...

在CSS中,有时候需要让几个盒子平均分布在一个容器中,这是一个非常常见的需求。下面介绍几种实现方法:

 /* 方法一:使用flexbox布局 */
.container {
  display: flex;
  justify-content: space-between;
}
.box {
  width: 30%;
}

/* 方法二:使用float布局 */
.container {
  overflow: hidden;
}
.box {
  width: 30%;
  float: left;
  margin-right: 3.3333%;
}
.box:last-child {
  margin-right: 0;
}

/* 方法三:使用表格布局 */
.container {
  display: table;
  width: 100%;
  border-spacing: 0 15px;
}
.box {
  width: 30%;
  display: table-cell;
}

/* 方法四:使用calc()计算宽度 */
.container {
  font-size: 0; /*消除空格*/
}
.box {
  width: calc((100% - 20px) / 3);
  margin-right: 20px;
  display: inline-block;
  vertical-align: top;
}
.box:last-child {
  margin-right: 0;
} 

以上几种方法都有各自的优缺点,可以根据实际需求选择最适合的方式来实现平均分布。

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

62845

帖子

12

小组

80

积分

站长交流