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

如何让一个CSS Grid仅占用另一个重叠CSS Grid的一行?

解决方案

要解决文本介绍被产品卡片遮挡的问题,我们需要调整桌面端的网格布局结构,确保文本介绍仅占用第一行,其余产品卡片排列在下方,避免重叠。以下是修改后的CSS代码及说明:

修改后的CSS代码

body {
  background: #eee;
}

.products {
  margin: 64px 32px;
}

.products__grid {
  display: flex;
  flex-wrap: nowrap;
  column-gap: 4px;
  margin: 0 -32px;
  overflow-x: scroll;
  scroll-snap-type: x mandatory;
  scroll-padding-left: 32px;
  scrollbar-width: none;
  -ms-overflow-style: none;
}

.product-card {
  background-color: white;
  box-sizing: border-box;
  display: flex;
  flex-shrink: 0;
  flex-direction: column;
  padding: 32px 32px 64px;
  width: 100%;
  max-width: 100%;
}

.product-card__title {
  color: black;
  display: flex;
  font-size: 1rem;
  padding: 0 32px;
}

.product-card--story {
  background-color: transparent;
  justify-content: center;
  padding: 0 32px;
  text-align: center;
}

@media only screen and (min-width: 800px) {

  .products {
    display: grid;
    column-gap: 4px;
    row-gap: 4px;
    margin: 64px 32px;
    grid-template-columns: repeat(12, 1fr);
    grid-template-rows: auto auto; /* 定义两行:第一行放文本和第一个产品,第二行放其余产品 */
  }

  .products__desc {
    background: rgba(255, 0, 0, .24);
    grid-column: 2 / span 4;
    grid-row: 1; /* 文本固定在第一行 */
  }

  .products__grid {
    display: grid;
    column-gap: 4px;
    row-gap: 4px;
    grid-template-columns: repeat(12, 1fr);
    grid-row: 1 / span 2; /* 让产品网格跨两行,包含第一行的第一个产品和第二行的其余产品 */
    grid-column: 1 / span 12;
    margin: 0;
    overflow-x: visible; /* 取消移动端的横向滚动 */
    scroll-snap-type: none;
  }

  .product-card {
    grid-column: span 4;
    grid-row: 2; /* 默认将产品卡片放在第二行 */
  }

  .product-card:first-child {
    grid-column: 9 / span 4;
    grid-row: 1; /* 第一个产品卡片放在第一行右侧 */
  }

  .product-card__title {
    color: black;
    display: flex;
    font-size: 1rem;
    padding: 0 32px;
  }

  .product-card--story {
    background-color: transparent;
    justify-content: center;
    padding: 0 32px;
    text-align: center;
  }

}

关键调整说明

  1. 父网格定义两行:给.products添加grid-template-rows: auto auto,明确分为两行,第一行高度由文本介绍或第一个产品卡片的高度决定(取最大值),第二行高度由其余产品卡片决定。

  2. 产品网格跨两行:设置.products__grid的grid-row: 1 / span 2,使其包含第一行的第一个产品和第二行的所有其他产品。

  3. 产品卡片默认放第二行:给.product-card添加grid-row:2,让除第一个外的所有产品卡片默认排列在第二行,仅第一个产品卡片通过grid-row:1放在第一行右侧,与文本介绍同行。

  4. 取消移动端滚动样式:在桌面端覆盖.products__grid的横向滚动相关属性,避免影响网格布局。

这样调整后,文本介绍会完全显示在第一行,不会延伸到第二行被产品卡片遮挡,同时保持了桌面端文本与第一个产品同行、其余产品换行的布局要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 12:57:34