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

不使用JavaScript能否实现Bootstrap卡片内对应元素高度均等对齐

解决方法

原方案问题

你之前给卡片内子元素设置flex:1/flex:2的逻辑是作用在单张卡片的独立flex容器内,比例是相对于单张卡片的总高度计算,因此不同卡片的同位置子元素高度无法统一。

纯CSS实现方案(无JS)

使用CSS Subgrid特性即可完美实现,这个特性专门用于跨多个容器同步网格轨道尺寸,正好匹配你要的所有卡片对应元素对齐的需求。

修改后的CSS代码:

.my-card {
  background-color: red;
  color: white;
  height: 100%;
  padding-top: 20px;
  padding-bottom: 20px;
  text-align: center;
  /* 删掉原有的flex相关属性即可 */
}
.img {
  width: 30px;
  height: 30px;
  background-color: blue;
  margin: 0 auto;
}
h2 {
  font-size: 72px;
}
h3 {
  font-size: 30px;
}
p {
  font-size: 20px;
}

/* 新增Subgrid相关样式 */
@media (min-width: 768px) {
  .row {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 1.5rem; /* 匹配Bootstrap默认列间距 */
    grid-template-rows: auto auto auto auto; /* 对应卡片内4个子元素的行轨道 */
  }
  .my-card {
    display: grid;
    grid-template-rows: subgrid; /* 继承父级row的行轨道,所有卡片行高自动同步 */
    grid-row: span 4; /* 单张卡片占满4行轨道 */
  }
}

兼容性说明

目前Subgrid在Chrome 117+、Firefox 71+、Safari 16+均已支持,覆盖90%以上的全球现代浏览器用户。如果需要兼容更低版本浏览器,可以根据内容最大长度给对应子元素设置最小高度兜底,例如:

h3 {
  min-height: 90px;
}
p {
  min-height: 220px;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 21:36:03