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

Bootstrap 4如何让每列宽度均等?解决商品列表最后一行拉伸问题

解决Bootstrap 4商品页面最后一行列拉伸问题

这个问题在响应式布局里太常见了——Bootstrap默认的col-sm会自动分配剩余空间,导致最后一行商品数量少的时候被强行拉满宽度。要实现所有商品宽高一致+动态适配屏幕,推荐用CSS Grid来替代传统的Bootstrap flex网格,或者给flex布局加一些自定义约束,下面分两种方案详细说:

方案一:CSS Grid(最推荐,简洁可靠)

CSS Grid的auto-fit + minmax组合完美适配你的需求——它会自动根据屏幕宽度调整每行商品数量,同时保证所有商品的宽度完全一致,最后一行也不会被拉伸。

步骤1:修改HTML结构

把原来的row容器换成自定义的网格容器,同时移除每个商品的col-sm类(因为Grid会自己管理列宽):

<div class="product-grid">
 <div class="product_cell">
 <img class="product_image" src="images/products/coke_can.png">
 <hr>
 <p class="product_name" style="text-align: center">Coca Cola 300 ml</p>
 <p class="product_price">€0.80</p>
 </div>
 <div class="product_cell">
 <img class="product_image" src="images/products/coke_can.png">
 <hr>
 <p class="product_name" style="text-align: center">Coca Cola 300 ml</p>
 <p class="product_price">€0.80</p>
 </div>
 <!-- 更多商品项 -->
</div>

步骤2:添加CSS样式

/* 网格容器:自动适配列数,最小列宽200px,列间距1rem */
.product-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 1rem; /* 替代原来的ml-2、mb-2,统一控制间距更方便 */
  padding: 0 0.5rem; /* 可选,给容器加左右内边距避免贴边 */
}

/* 商品卡片:保证高度一致 */
.product_cell {
  display: flex;
  flex-direction: column;
  height: 100%; /* 让每个卡片占满网格单元格的高度 */
  border: 1px solid #eee; /* 可选,加个边框更美观 */
  padding: 1rem;
  border-radius: 4px;
}

/* 商品图片:固定比例,避免拉伸变形 */
.product_image {
  width: 100%;
  height: 180px; /* 根据你的需求调整高度 */
  object-fit: cover; /* 保持图片比例,裁剪多余部分 */
  margin-bottom: 0.5rem;
}

/* 文字区域:填充剩余空间,保证高度一致 */
.product_name, .product_price {
  flex-grow: 1; /* 让文字部分自动填充卡片剩余高度 */
  text-align: center; /* 可以把内联样式移到这里,更整洁 */
}

.product_price {
  font-weight: bold;
  color: #dc3545; /* 可选,价格用醒目颜色 */
}

方案二:Bootstrap Flex布局兼容方案

如果你不想完全抛弃Bootstrap的flex网格,可以给col-sm添加自定义约束,限制它的拉伸行为:

修改后的HTML

<div class="row row-spacing">
 <div class="col-sm product-col product_cell">
 <!-- 商品内容不变 -->
 </div>
 <div class="col-sm product-col product_cell">
 <!-- 商品内容不变 -->
 </div>
 <!-- 更多商品项 -->
</div>

添加CSS样式

.product-col {
  flex: 1 1 200px; /* 允许拉伸/收缩,最小宽度200px */
  max-width: calc(100% / 3); /* 可选:限制每行最多3个商品,根据需求调整 */
}

/* 同样要保证卡片高度一致 */
.product_cell {
  display: flex;
  flex-direction: column;
  height: 100%;
}

/* 图片和文字的样式和方案一一致 */
.product_image {
  width: 100%;
  height: 180px;
  object-fit: cover;
  margin-bottom: 0.5rem;
}

.product_name, .product_price {
  flex-grow: 1;
  text-align: center;
}

注意:这个方案下,如果最后一行只有1个商品,它还是会拉伸到接近满宽(因为flex-grow:1),如果要避免这种情况,还是方案一的CSS Grid更稳妥。

关键说明

  • 宽度一致:CSS Grid的1fr会让所有列均等分配空间,不管每行有几个商品,宽度都完全相同;
  • 高度一致:给商品卡片设置display:flex + flex-direction:column + height:100%,再让文字区域flex-grow:1,就能保证所有卡片高度一致;
  • 动态适配:minmax(200px, 1fr)会自动在屏幕宽度足够时增加每行商品数量,宽度不够时自动换行,完美适配iPad到台式机的各种尺寸。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:35:24