2011-02-16 84 views
0

,我想了解一下下面的代碼:CSS和重寫樣式只能部分

<html> 
     <head> 
     <title>Test HTML</title> 
     <link rel="stylesheet" type="text/css" href="test.css"> 
     </head> 
<body> 
<table class=foo cellpadding="2" cellspacing="2"> 
     <tr> 
      <td><b>Contingency Table:</b></td> 
      <td><table class=bar border="2" align="left"> 
        <tr><td>blaa</td><td>blaa</td><td>blaa</td></tr> 
        <tr><td>blaa</td><td>blaa</td><td>blaa</td></tr> 
        <tr><td>blaa</td><td>blaa</td><td>blaa</td></tr> 
       </table> 
      </td> 
     </tr> 
</table> 
</body> 
</html> 

與下面的CSS:

table { 
     border-width: 2px; 
     border-spacing: 2px; 
     border-style: solid; 
     } 

table.bar { 
     border-color: red; 
     background-color: white; 
} 

table.bar td { 
     background-color: green; 
} 

table.bar tr { 
     background-color: black; 
} 

table.foo { 
     border-color: blue; 
     background-color: white; 
} 

table.foo td { 
     border-color: black; 
     background-color: yellow; 
} 

table.foo tr { 
     background-color: yellow; 
} 

的問題是,互換類時,「富「和」bar「在表格及其嵌套表格中,td-tags的風格沒有正確設置,或者至少與我預期的不同。當從外部「bar」和內部「foo」更改爲外部「foo」和內部「bar」時,除了td元素的顏色外,顏色會按預期更改。我在這裏做錯了什麼,因爲表格的其他元素更改正確?

我知道使用table table.foo {...}可以工作,但這需要知道內部/嵌套表應使用哪種樣式,我不太喜歡這個想法。我希望能夠在需要時交換樣式,並且不在樣式表中包含「繼承」...此外,在樣式表中指定foo或bar樣式的順序對我來說也是不可取的。請糾正我,如果這實際上是常見的HTML/CSS的做法。

回答

3

CSS - 級聯樣式表!簡而言之,如果您在表中切換foo和bar類,則還需要將table.foo css規則移動到table.bar類之上。

解釋如果bar嵌套在foo的CSS規則table.foo td同時匹配TDS同時在foobar表。所以它的table.foo td是在table.bar td規則之後聲明的,table.foo td規則覆蓋table.bar td

+0

謝謝。但爲什麼然後做表和tr工作,但不是td? – Shadow 2011-02-16 12:11:09

+1

我不認爲這是。實際上,tr規則和td規則的顏色看起來是相同的。所以實際上你看到的是td規則。我認爲在tr上設置`background-color`實際上並不適用於所有主流瀏覽器。 – xzyfer 2011-02-16 12:15:56

2

xzyfer的推理是正確的。簡單的解決方法可能是添加

table table.bar td { background-color: green !important; } 

假設你的嵌套最多2級,這工作得很好,因爲它覆蓋描述的級聯效應(即應用的規則不再依賴訂單上的規則被定義)。

工作例如:http://jsfiddle.net/RQCQS/

0

如果你只想要一拖效果,你需要一些子選擇表foo的直接孩子。 您可能需要查看,因爲我知道它們可以用作舊版瀏覽器的解決方案。另外我建議將TBODY你的表作爲Firefox會自動執行此操作,它搞砸了我的孩子選擇的測試:

table.foo > tbody > tr > td { 
     border-color: black; 
     background-color: yellow; 
} 

table.bar > tbody > tr > td { 
     background-color: green; 
} 

應該工作在Firefox,你就必須測試其他瀏覽器。 你遇到的問題已在其他帖子中解釋過,但它是級聯樣式表的性質,因爲你的代碼最初是table.foo中的任何td受到樣式table.foo td的影響。或者,您將不得不切換樣式的順序,以便嵌套樣式總是覆蓋外部樣式。