使用nth-child设置4列奇数偶数网格,然后选择项2、4、5、7、10、12、13、15、18、20

时间:2018-10-15 14:42:46

标签: css html5 css3 css-selectors

我为要达到的目的添加了静态代码,但我需要将此代码动态化,以便可以检测到这些子代2、4、5、7、10、12、13、15、18、20。使用“第n个孩子”。所有的子元素都必须在单个父div中,并且不能在div的不同行中。

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

我正在创建类似上述结构的内容,并且希望仅使用nth-child将相同背景应用于粗体文本。

.PlayersGridItem__row {
  display: flex;
  width:100%;
  flex-wrap: wrap;
}
.PlayersGridItem__item {
  width: 25%;
  position: relative;
  border:1px solid red;
  background: #cccccc;
  padding: 30px;
  box-sizing:border-box;
}
.PlayersGridItem__item:nth-child(2)
  {
  background:#FFF;
  }
  
  .PlayersGridItem__item:nth-child(4)
  {
  background:#FFF;
  }
  
.PlayersGridItem__item:nth-child(5)
  {
  background:#FFF;
  }
  
.PlayersGridItem__item:nth-child(7)
  {
  background:#FFF;
  }
<div class="PlayersGridItem__row">
            <div class="PlayersGridItem__item">
              <div class="PlayersGridItem__player-name">
                Noah Andrews
              </div>

            </div>
            <div class="PlayersGridItem__item">
              <div class="PlayersGridItem__player-name">
                Noah Andrews
              </div>

            </div>
            <div class="PlayersGridItem__item">
              <div class="PlayersGridItem__player-name">
                Noah Andrews
              </div>

            </div>
            <div class="PlayersGridItem__item">
              <div class="PlayersGridItem__player-name">
                Noah Andrews
              </div>
            </div>
            <div class="PlayersGridItem__item">
              <div class="PlayersGridItem__player-name">
                Noah Andrews
              </div>

            </div>
            <div class="PlayersGridItem__item">
              <div class="PlayersGridItem__player-name">
                Noah Andrews
              </div>

            </div>
            <div class="PlayersGridItem__item">
              <div class="PlayersGridItem__player-name">
                Noah Andrews
              </div>

            </div>
            <div class="PlayersGridItem__item">
              <div class="PlayersGridItem__player-name">
                Noah Andrews
              </div>
            </div>
          </div>

1 个答案:

答案 0 :(得分:1)

您可以尝试定位奇/偶行及其奇/偶子对象。假设每行数字都是一个单独的.row,而每个数字都是一个.column

.row:nth-child(odd) .column:nth-child(even),
.row:nth-child(even) .column:nth-child(odd) {
    background-color: blue;
}