【问题标题】:How to lay my articles in a checkerboard pattern using CSS grids?如何使用 CSS 网格以棋盘模式放置我的文章?
【发布时间】:2023-02-15 20:51:51
【问题描述】:

我有这个 HTML:

<div class="container">
  <article>
    <div class="one">ONE</div> <div class="two">TWO</div>
  </article>
  <article>
    <div class="one">ONE</div> <div class="two">TWO</div>
  </article>
  <article>
    <div class="one">ONE</div> <div class="two">TWO</div>
  </article>
  <article>
    <div class="one">ONE</div> <div class="two">TWO</div>
  </article>
   ....
</div>  

这是我的 CSS

.container{
  width: 400px;
  display: grid;
  grid-template-columns: 1fr 50%;
}
article div{
  padding: 5px;
}
article .one{background: red;}
article .two{background: blue;}

article{
  display: grid;
  grid-template-columns: 1fr 55%;
}

article:nth-child(3n+1)  .two{
    order: -1
}

如您所见,我唯一能想到的就是玩 nth-child 但结果并不好,有没有办法解决它(最好不要向 HTML 添加额外的 div)

Here's my live code

【问题讨论】:

    标签: javascript html css


    【解决方案1】:

    试试这个CSS:

    .container {
      width: 400px;
      display: grid;
      grid-template-columns: 1fr 50%;
      grid-auto-rows: 50px; /* set the height of the rows */
      grid-gap: 10px; /* add some space between the articles */
    }
    
    article {
      display: grid;
      grid-template-columns: 1fr 55%;
      grid-row: span 2; /* span 2 rows */
    }
    
    /* alternate the background colors of the articles */
    article:nth-child(even) .one {
      background-color: red;
    }
    article:nth-child(odd) .one {
      background-color: blue;
    }
    
    /* position the articles in a checkerboard pattern */
    article:nth-child(4n+1),
    article:nth-child(4n+4) {
      grid-column: 1 / 3;
    }
    
    article:nth-child(4n+2),
    article:nth-child(4n+3) {
      grid-column: 2 / 3;
    }
    

    在这段代码中,grid-auto-rows 属性设置了行的高度,grid-gap 在文章之间增加了一些空间。

    grid-row 属性用于为每篇文章跨越两行,从而创建棋盘格图案。

    第 n 个子选择器用于交替 .one div 的背景颜色,并使用 grid-column 属性将文章定位在棋盘图案中。

    结果是一个棋盘图案,其中所有其他文章的列都颠倒了,并且 .one div 的背景颜色在红色和蓝色之间交替。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多