2014-03-06 37 views
1

也許有一個奇怪的問題,但我想用CSS3來做到這一點,但我不知道是否有可能。我試圖用nth-childnth-of-type進行實驗,但是我無法使其工作。我想這很難得到我想要的而不使用Javascript。使用CSS3給每三個錶行一個背景顏色

總之,讓我告訴你我想要什麼......

我有一個table 3個<tr>元素,我想給一個背景顏色。在這些表格行下面,我們有三個表格行。那些不會有不同的顏色。問題:你如何選擇他們?有evenodd,這是不可能的...但是否有可能結合第n類型與偶數或奇數?還是這個烏托邦?

我知道我可以給這些行一個類並使其工作,但這不是我所追求的目標。想用CSS3解決它,即使IE不支持它。有沒有辦法做到這一點?

HTML:

<table class="dummyclass"> 
     <tbody> 
      <tr class="This_should_get_a_background_color"> 
        <th>Dummytext</th> 
        <td><a href="#">Dummy dummy</a></td> 
      </tr> 
      <tr class="This_should_get_a_background_color"> 
        <th>Dumminho</th> 
        <td>Golazo</td> 
      </tr> 
      <tr class="This_should_get_a_background_color"> 
        <th>Great game</th> 
        <td>yesterday</td> 
      </tr> 

      <tr class="no-background-please"> 
        <th>Dummytext</th> 
        <td><a href="#">Dummy dummy</a></td> 
       </tr> 
       <tr class="no-background-please"> 
       <th>Dumminho</th> 
       <td>Golazo</td> 
       </tr> 
       <tr class="no-background-please"> 
       <th>Great game</th> 
       <td>yesterday</td> 
       </tr> 

      <tr class="This_should_get_a_background_color"> 
       <th>Dummytext</th> 
       <td><a href="#">Dummy dummy</a></td> 
      </tr> 
      <tr class="This_should_get_a_background_color"> 
        <th>Dumminho</th> 
        <td>Golazo</td> 
      </tr> 
      <tr class="This_should_get_a_background_color"> 
        <th>Great game</th> 
        <td>yesterday</td> 
       </tr> 
      </tbody> 
      </table> 

而對於CSS,以及我嘗試了很多東西像tr:nth-of-type(2n+1),但我看到這裏,是不是我的選擇:http://css-tricks.com/examples/nth-child-tester/

對於小提琴,請點擊這裏:http://jsfiddle.net/95vrb/1/

我給出了行描述性的類名,這樣你就可以理解我正在嘗試做什麼。

回答

3

有可能是一個更好的方式做到這一點,但這個工程。 基本上它會爲每個第六個孩子添加背景,從第一,第二和第三個元素開始。

http://jsfiddle.net/95vrb/2/

tr:nth-child(6n + 3), 
tr:nth-child(6n + 2), 
tr:nth-child(6n + 1) { 
    background: #f00; 
} 

我覺得這是一個很好的介紹:nth-childhttp://css-tricks.com/how-nth-child-works/

+0

沒想到那麼簡單。謝啦! – Siyah

1

您可以使用此:

.dummyclass tr:nth-of-type(-n+3), //First three rows 
.dummyclass tr:nth-of-type(n+7) { //Last three rows 
    background: #aaa; 
} 

小提琴:http://jsfiddle.net/Shiazure/95vrb/5/

當然,這一世s是根據您給出的示例量身定製的,並且需要根據單元格/行數進行更改。

+0

這沒有得到最後三行。只有前三個 – Mathias

+0

@Mathias是的,我糾正它,對不起。 –

+0

謝謝你的回答。我upvoted它! – Siyah