2010-10-08 99 views
5

在下面的HTML/CSS中,爲什麼鏈接顏色是綠色而不是藍色,即爲什麼「p.description」重寫「#nav」但「p.description a」不重寫「#nav a」?爲什麼超鏈接樣式不能在CSS中級聯?

alt text

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> 
<title>Insert title here</title> 
<style type="text/css"> 
    #nav { 
     color: black; 
    } 
    #nav a { 
     color: green; 
    } 
    p.description { 
     color:red; 
    } 
    p.description a { 
     color:blue; 
    } 
</style> 
</head> 
<body> 
    <div id="nav"> 
     <p class="description">This is a test and <a href="#">this is a link</a>.</p> 
    </div> 
</body> 
</html> 
+0

相關:http://stackoverflow.com/questions/2809024/points-in-css-specificity – 2010-10-08 15:40:31

回答

13

因爲id選擇加上一個類型選擇爲超過兩個類型的選擇器和一個類選擇更具體。請參閱the specification on specificity

因此,它會級聯,但級聯發生順序的規則並不是您認爲的那樣。

+4

只是爲了增加價值的回答,他可以更具體地通過改變他的選擇器爲'#nav p.description a' – 2010-10-08 15:42:14

+0

謝謝喬希那是我正在尋找的修復 – 2010-10-08 15:43:38

-3

它的綠色,因爲css規則#nav a {color:green;}規定它。

爲了讓藍做到這一點#nav一個{顏色:藍色;}

+1

這並不回答這個問題。他想知道爲什麼它的行爲如此,他只想要在說明段落中的藍色鏈接。 – 2010-10-08 15:43:44