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

CSS Grid布局中解决.separator元素高度被拉伸的问题

解决CSS Grid中分隔符被过度拉伸的问题

你设置的grid-auto-rows: 1fr会让Grid自动创建的所有行高度统一为1fr,而.separator默认会拉伸填满所在行的高度,导致它被过度放大。下面提供两种可行的解决办法:

方法一:给分隔符设置对齐方式

给.separator添加align-self: start(也可选择center或end,根据布局需求调整),让它保持自身高度,不强制填满整行:

* {
  font-family: Verdana;
}

.grid {
  --grid-item-width: 116px;

  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(var(--grid-item-width), 1fr));
  grid-auto-rows: 1fr;
  gap: 20px;
}
  
.separator {
  grid-column: 1 / -1;
  padding: 4px 10px;
  height: 22px;
  line-height: 22px;
  background-color: #CCC;
  border-radius: 8px;
  vertical-align: middle;
  align-self: start; /* 新增:让分隔符保持自身高度 */
}

.item {
  display: flex;
  flex-direction: column;
  justify-content: end;
  align-items: stretch;
  background-color: #CCC;
  text-align: center;
  border-radius: 8px;
  overflow: hidden;
  line-height: 30px;
}
    
.item img {
  aspect-ratio: 1 / 1;
  width: 100%;
}

方法二:调整Grid行高规则

将grid-auto-rows: 1fr改为grid-auto-rows: auto,同时给.item设置height: 100%,让同一行的.item自动填满行高(行高由该行最高的.item决定),.separator所在行的高度会自适应它的内容:

* {
  font-family: Verdana;
}

.grid {
  --grid-item-width: 116px;

  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(var(--grid-item-width), 1fr));
  grid-auto-rows: auto; /* 修改为auto */
  gap: 20px;
}
  
.separator {
  grid-column: 1 / -1;
  padding: 4px 10px;
  height: 22px;
  line-height: 22px;
  background-color: #CCC;
  border-radius: 8px;
  vertical-align: middle;
}

.item {
  display: flex;
  flex-direction: column;
  justify-content: end;
  align-items: stretch;
  background-color: #CCC;
  text-align: center;
  border-radius: 8px;
  overflow: hidden;
  line-height: 30px;
  height: 100%; /* 新增:让项目填满行高 */
}
    
.item img {
  aspect-ratio: 1 / 1;
  width: 100%;
}

两种方法的区别:

  • 方法一保留了所有项目行高度统一的特性,适合需要严格对齐的场景;
  • 方法二的行高由内容动态决定,更灵活,适合不同组项目高度差异较大的情况。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 19:17:12