You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使4个Card的左右间距与Section1完全一致?

解决响应式布局中Section2卡片与Section1对齐问题

问题分析

Section1的布局是30% 图片容器 + 1% 左间距 + 69% 内容容器,总宽度刚好占满100%,内容容器的右边缘与父容器完全对齐。而当前Section2的4个卡片设置24% 宽度 + 1% 右margin时,总宽度为24%*4 + 1%*3 = 99%,右侧会多出1%的空白,导致无法与Section1对齐。

解决方案

以下三种方法都能实现卡片左右边距与Section1完全对齐,按推荐程度排序:

1. Flex布局(最简洁推荐)

利用Flexbox的flex:1自动分配空间,配合gap控制卡片间距:

.section2 {
  display: flex;
  gap: 1%; /* 与Section1的间距保持一致 */
}

.section2 .card {
  flex: 1; /* 四个卡片平分剩余宽度 */
}

Flex会自动计算每个卡片的宽度为(100% - 3*1%)/4,既保证间距一致,又让最后一个卡片的右边缘与Section1对齐。

2. 手动计算宽度与margin

如果不使用Flex,可通过精确计算实现:
四个卡片之间有3个1%的间隙,总间隙占3%,剩余可用宽度为97%,每个卡片宽度为97%/4 = 24.25%,仅给前三个卡片设置右margin:

.section2 .card {
  width: 24.25%;
  float: left;
}

.section2 .card:not(:last-child) {
  margin-right: 1%;
}

若使用inline-block实现横向排列,需给父容器添加font-size: 0消除卡片间的空白节点影响。

3. CSS Grid布局

用Grid的列分配和gap属性快速实现:

.section2 {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 1%;
}

Grid会自动将父容器宽度减去3个1%的间隙后,平均分配给4个卡片,确保整体布局与Section1对齐。

内容的提问来源于stack exchange,提问作者Heli Bhadeshiya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 13:40:34