2015-12-21 80 views
0

我在CSS這兩種風格,無論是在外部鏈接的CSS文件,並應用於同一個表,帶班myTable的(這是一個更大的問題的簡化版本):CSS特效法則麻煩

.myTable th 
{ 
    background-color: gray; 
} 

.myTable tr:nth-child(odd) 
{ 
    background-color: blue; 
} 

當我運行該頁面時,標題爲灰色,但爲什麼?我想知道的是爲什麼第一條規則是覆蓋第二條規則。如果我理解了很好的特異性計算(顯然我沒有),第二條規則更具體(所有計算器在第二條規則中給我0,1,2和第一條規則中的0,1,1)。爲什麼然後,如果第二條規則具有更多特異性,則標題是灰色而不是藍色?請有人能幫我理解這一點嗎?謝謝你非常非常......

+0

你現在明白了嗎? –

+0

男人,你在嗎? –

回答

3

你忘thtd

.myTable tr:nth-child(odd) th, 
.myTable tr:nth-child(odd) td { 
    background-color: blue; 
} 

,因爲你在你的第一類申請th,您需要使用在這裏。 thtr之內,所以無論你放什麼,th都會在前面顯示灰色。

0

您的第一條規則不會覆蓋第二條規則。

原因是您的標題爲灰色是因爲它包含th元素,並且您只爲th元素指定background: grey。 (並且thtr不相同)。

如果你想在你的頭交替柱的顏色也,然後修改代碼以解決thtd,像這樣:

.myTable th { 
    background-color: gray; 
} 

.myTable td:nth-child(odd), 
.myTable th:nth-child(odd) { 
    background-color: blue; 
} 
+2

是的,謝謝...我把一個透明的顏色(rgba)添加到標題中,我看到後面的藍色,所以這意味着CSS正在將標題畫在「超過」tr ...非常感謝你... –

+0

@AlanEspinet你看到我的答案了嗎? –

1

CSS的特異性並不在您的情況適用。

你的CSS面向兩個不同的元素; thtr

你必須從角度思考這個問題。

由於th的被包含在tr的那麼thbackground-color將上述的trbackground-color顯示

採取此代碼爲例如:

<tr style="background-color: gray"> 
    <th>Heading One</th> 
    <th style="background-color: red">Heading Two</th> 
    <th>Heading Three</th> 
</tr> 

第一和第三th具有透明background-color,所以trbackground-color示出了通過它們。第二個th有一個background-color定義,因此它顯示如預期。

你可以看看這個jsfiddle看到它在行動。