两列与CSS的替代颜色

时间:2015-04-20 09:29:10

标签: html css3 grid

我试图用替代颜色创建一个2列网格(第一个单元格为红色,第二个为黄色,第三个为黄色,第四个为红色等等)

使用3 cols网格我没有问题,但有了这种布局,我会发疯= _ =

有人可以帮助我吗?

由于

BRK

1 个答案:

答案 0 :(得分:2)

您可以使用此选择器:nth-child()

/*Every 2 rows from 0 (even) - Every 2 cells from 0 (even)*/
.row:nth-child(2n+0) div:nth-child(2n+0) { 
    background: #ff0000;
}

/*Every 2 rows from 0 (even) - Every 2 cells from 1 (odd)*/
.row:nth-child(2n+0) div:nth-child(2n+1) {
    background: #ffff00;
}

/*Every 2 rows from 1 (odd) - Every 2 cells from 0 (even)*/
.row:nth-child(2n+1) div:nth-child(2n+0) {
    background: #ffff00;
}

/*Every 2 rows from 1 (odd) - Every 2 cells from 1 (odd)*/
.row:nth-child(2n+1) div:nth-child(2n+1) {
    background: #ff0000;
}
  

Demo

可以像这样简化:

.row:nth-child(even) div:nth-child(even) {
    background: #ff0000;
}
.row:nth-child(even) div:nth-child(odd) {
    background: #ffff00;
}
.row:nth-child(odd) div:nth-child(even) {
    background: #ffff00;
}
.row:nth-child(odd) div:nth-child(odd) {
    background: #ff0000;
}
  

Demo


  

Documentation