解决使用 justify-content: space-between 时两个卡片分居两侧的问题

95 阅读1分钟

使用 justify-content: flex-start + 动态边距(推荐)

核心思路:改用左对齐布局,通过设置卡片间距并清除每行最后一个卡片的右边距。

.container {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start; /* 改为左对齐 */
}

.card {
  width: calc(33.33% - 20px); /* 减去间距 */
  margin-right: 20px; /* 卡片间距 */
  margin-bottom: 20px;
}

/* 清除每行第3个卡片的右边距 */
.card:nth-child(3n) {
  margin-right: 0;
}

/* 清除最后一行的最后一个卡片边距(无论剩余几个) */
.card:last-child {
  margin-right: 0;
}

优点

  • 兼容所有浏览器
  • 两个卡片相邻显示(间距20px),不会分居两侧
  • 自动适应任意数量卡片(1个、2个、3个)