2012-08-23 106 views
4

我遇到了CSS聲明優先級的問題。我的頁面包含一個帶有規則和一些內聯CSS聲明的外部CSS文件,它們應該覆蓋該規則。據我的理解,內聯樣式聲明應該重寫外部CSS聲明。但是,當我在Chrome瀏覽器中查看頁面時,表格的第二行顯示爲藍色,應該按照內部樣式聲明中的定義顯示紅色。Css風格優先

缺少什麼我在這裏

下面是HTML:

<html> 
<head> 
    <link rel="stylesheet" href="screen.css" type="text/css" media="screen, projection"> 
    <style type="text/css"> 
     td,tr,th 
     { 
      background: Red; 
     } 
    </style> 
</head> 
<body> 
    <table> 
     <tr> 
      <td>11</td> 
      <td>22</td> 
     </tr> 
     <tr> 
      <td>aa</td> 
      <td>bb</td> 
     </tr> 
    </table> 
</body> 
</html> 

這裏是CSS文件的內容:

tbody tr:nth-child(even) td, 
tbody tr.even td 
{ 
    background: #e5ecf9; 
} 
+0

你應該_avoid_'important' - 見http://stackoverflow.com/questions/3706819/what-are-the-implications! -of-using-important-in-css – andyb

回答

12

的選擇事項數計算其規則時具有最高的特異性。 CSS特異性

兩個出色的可視化是http://www.standardista.com/css3/css-specificity/http://www.stuffandnonsense.co.uk/archives/css_specificity_wars.html

你應該避免只是在規則堅持!important覆蓋(見What are the implications of using "!important" in CSS?),而是改變選擇,讓您的規則更多或相等的權重,以進口規則。

例如下面將讓所有的細胞background:red

thead tr:nth-child(1n) th, tbody tr:nth-child(1n) td { 
    background:red; 
} 
+0

這不會在這種情況下工作。看看我的答案。 :-) – Raisch

+0

@Raisch是的謝謝。發現這只是在本地測試正確的選擇器:-) – andyb

+0

沒問題。現在它會工作。 :-D – Raisch

1

在這種情況下,更詳細的規則將得到它。

在你的HTML試試這個:

<style type="text/css" media="screen, projection"> 
    tbody tr:nth-child(even) td,tr,th 
    { 
     background: Red; 
    } 
</style> 

問候

+0

+1不錯的解決方案。比我的混亂更少 – andyb

+1

該代碼具有誤導性,因爲部分',tr,th'沒有影響,其作用很容易被誤解。這裏重要的是對特定「td」元素的設置,使用足夠大的特異性。 –

+0

@ JukkaK.Korpela - 我知道,我只是擴展了自己的CSS塊。 :-) – Raisch