2014-10-22 115 views
2

我想要實現具有交替顏色的網格塊的兩列網格佈局。但是,通過一個簡單的孩子(奇數)或者孩子(偶數)實現這一點並不會成功。交替網格顏色

我非常確定我想要什麼可以實現使用一個nth孩子欺騙,而不是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; 
    } 

} 

回答

4

當重複的圖案每隔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; 
    } 
} 
+0

的jsfiddle演示 - http://jsfiddle.net/wby22zay/ – 2014-10-22 10:23:59

+0

驚人的...謝謝! – 2014-10-22 11:06:28