首页 > 解决方案 > 构建 CSS 网格模板的问题

问题描述

我尝试构建以下 css 网格模板,但在最后 3 个项目上苦苦挣扎。

有没有人想办法解决这个问题?

我认为问题可能是第二行的高度(项目 4,5,6)

.grid {
    display: grid;
    grid-gap: 30px;
    grid-template-columns: repeat(12, 1fr);

    .col {
        
        &:nth-child(10n+1),
        &:nth-child(10n+2),
        &:nth-child(10n+10) {
            grid-column: auto / span 3;
            height: 580px;
            background-color: red;
        }

        &:nth-child(10n+3),
        &:nth-child(10n+7) {
            grid-column: auto / span 6;
            height: 580px;
            background-color: yellow;
        }
        
        &:nth-child(10n+4),
        &:nth-child(10n+5),
        &:nth-child(10n+6) {
            grid-column: auto / span 4;
            height: 430px;
            background-color: green;
        }

        &:nth-child(10n+8),
        &:nth-child(10n+9) {
            grid-column: auto / span 3;
            height: 275px;
            background-color: blue;
        }
    }
}

模板:

模板

结果:

结果

标签: csscss-grid

解决方案


你几乎很好,你只需要调整最后一个蓝色 div 的开始,使其低于第一个。您还可以更改设置高度的方式,如下所示:

.grid {
  display: grid;
  grid-gap: 30px;
  grid-template-columns: repeat(12, 1fr);
  grid-auto-flow:dense; /* this will fix the position of the last red */
}

.grid .col:nth-child(10n+1),
.grid .col:nth-child(10n+2),
.grid .col:nth-child(10n+10) {
  grid-column: span 3;
  grid-row: span 2; /* take two rows */
  background-color: red;
  height:200px; /* define the height for only the red and the blue, yellow will follow */
}

.grid .col:nth-child(10n+3),
.grid .col:nth-child(10n+7) {
  grid-column:span 6;
  grid-row: span 2; /* also take two rows */
  background-color: yellow;
}

.grid .col:nth-child(10n+4),
.grid .col:nth-child(10n+5),
.grid .col:nth-child(10n+6) {
  grid-column:span 4;
  background-color: green;
  height:150px; /* the green are alone so they need a height */
}

.grid .col:nth-child(10n+8),
.grid .col:nth-child(10n+9) {
  grid-column-end: span 3;
  background-color: blue;
}
/* this will fix your issue */
.grid .col:nth-child(10n+9) {
  grid-column-start:7
}
/* */
<div class="grid">
  <div class="col"></div>
  <div class="col"></div>
  <div class="col"></div>
  <div class="col"></div>
  <div class="col"></div>
  <div class="col"></div>
  <div class="col"></div>
  <div class="col"></div>
  <div class="col"></div>
  <div class="col"></div>
</div>


推荐阅读