2013-02-21 96 views
48

我想斑馬條紋我的網站在我的div,聽起來很簡單,但我發現,當我在我的divs行之間添加標題時,它似乎計數在奇/偶造型CSS div交替顏色

HTML

<div class="container"> 
    <h3>Title</h3> 
    <div class="row">Content</div> 
    <div class="row">Content</div> 
    <h3>Title</h3> 
    <div class="row">Content</div> 
    <div class="row">Content</div> 
    <div class="row">Content</div> 
    <h3>Title</h3> 
    <div class="row">Content</div> 
    <div class="row">Content</div> 
    <div class="row">Content</div> 
    <div class="row">Content</div> 
</div> 

CSS

.container { 
    width:600px; 
    margin:0 auto; 
} 

.row { 
    line-height:24pt; 
    border: solid 1px black; 
} 

.row:nth-child(odd) { 
    background: #e0e0e0; 
} 

h3 { 
    line-height:36pt; 
    font-weight:bold; 
    color:blue; 
} 

fiddle

我會認爲已經在小提琴中的代碼基本上會忽略標題並進行分條,但它似乎認爲標題是小孩

回答

85

不要使用nth-child,使用nth-of-type

div.container > div:nth-of-type(odd) { 
    background: #e0e0e0; 
} 

jsFiddle example

+1

當然,謝謝。 – 2013-02-21 14:36:18

+2

請注意,這個「繼續」通過標題進行計數。如果您想「重置」計數器(例如,使標題後的第一行始終爲白色),則需要使用Jezen的解決方案。 – 2013-02-21 14:45:43

+0

@ j08691我可以知道爲什麼最好使用n型而不是n型?只是好奇。 – Musikero31 2018-02-27 03:01:12

5

最簡單的解決方案當然是將您的元素想要條紋。

Your updated jsFiddle

HTML

<div class="container"> 
    <h3>Title</h3> 
    <div class="zebra"> 
     <div class="row">Content</div> 
     <div class="row">Content</div> 
    </div> 
    <h3>Title</h3> 
    <div class="zebra"> 
     <div class="row">Content</div> 
     <div class="row">Content</div> 
     <div class="row">Content</div> 
    </div> 
    <h3>Title</h3> 
    <div class="zebra"> 
     <div class="row">Content</div> 
     <div class="row">Content</div> 
     <div class="row">Content</div> 
     <div class="row">Content</div> 
    </div> 
</div> 

CSS

.row:nth-child(odd) {background: #e0e0e0;} 

請記住還,如果browser support對你很重要,你可能想生成斑馬條紋服務器端,而不是其他類。

+0

這樣,這是低效的,如果他想增加更多的還是用這個評論系統,使其更容易看到不同的意見......他希望應該是動態的 – 2013-02-21 14:33:32

+0

沒有理由爲什麼這不能動態。 – 2013-02-21 15:03:07

+0

帶有容器的包裝元素並將css應用於該容器的類效率不高,而不是第n個子方法。 – 2013-02-24 01:40:57

6

你可能想匹配類型,而不是孩子。

使用:第n-的型作爲

.row:nth-of-type(odd) { 
    background: #e0e0e0; 
}