【问题标题】:Alternating grid colours交替网格颜色
【发布时间】:2014-12-17 15:45:56
【问题描述】:

我想要实现具有交替颜色的网格块的两列网格布局。然而,用一个简单的 nth-child(odd) 或 nth-child(even) 来实现这一点不会成功。

我很确定可以使用一些 nth-child 技巧而不是 JS 解决方案来实现我想要的,但不太确定如何。

这是我想要实现的目标:http://codepen.io/abbasinho/pen/Gbnze

这是笔中的 HTML,我想避免额外的类来添加颜色:

<div class="grid-holder">
  <div class="grid red"></div>
  <div class="grid blue"></div>
  <div class="grid blue"></div>
  <div class="grid red"></div>
  <div class="grid red"></div>
  <div class="grid blue"></div>
  <div class="grid blue"></div>
  <div class="grid red"></div>
</div>

SASS:

.grid-holder {
  width: 50%;
  margin: 0 auto;
  overflow: hidden;
}

.grid {
  width: 50%;
  height: 200px;
  float: left;

    &.red {
      background: red;
    }

    &.blue {
      background: blue;
    }

}

【问题讨论】:

    标签: html css layout grid css-selectors


    【解决方案1】:

    当您每 4 个元素(红/蓝/蓝/红)重复一个模式时,您可以通过 :nth-child(4n+x) 变化来实现这一点:

    <div class="grid-holder">
    
      <div class="grid"></div>
      <div class="grid"></div>
      <div class="grid"></div>
      <div class="grid"></div>
      <div class="grid"></div>
      <div class="grid"></div>
      <div class="grid"></div>
      <div class="grid"></div>
    
    </div>
    
    .grid-holder {
        width: 50%;
        margin: 0 auto;
        overflow: hidden;
    }
    
    .grid {
        width: 50%;
        height: 200px;
        float: left;
        background: red;
    
        // The 2nd and the 3rd element in our pattern will be blue
        &:nth-child(4n+2),
        &:nth-child(4n+3) {
            background: blue;
        }  
    }
    

    【讨论】:

    • 太棒了...谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-20
    • 1970-01-01
    • 2011-02-25
    相关资源
    最近更新 更多