[英]CSS & Overriding Styles on Nested Elements works only partially
我想知道以下代碼:
<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;
}
問題是,當交換表及其嵌套表中的“ foo”和“ bar”類時,td-tags的樣式設置不正確,或者至少不符合我的期望。 當從外部“ bar”和內部“ foo”更改為外部“ foo”和內部“ bar”時,除了td元素的顏色外,顏色會按預期更改。 由於表的其他元素正確更改,我在這里做錯了什么?
我知道使用table table.foo {...}
是可行的,但這需要知道內部/嵌套表應該使用哪種樣式,我並不真正喜歡這個想法。 我希望能夠在需要時交換樣式,而不在樣式表中包括“繼承” ...另外,我也不希望在樣式表中指定foo或bar樣式的順序。 如果這實際上是常見的HTML / CSS做法,請糾正我。
CSS- 級聯樣式表!
簡而言之,如果您在表中切換foo和bar類,則還需要將table.foo
css規則table.bar
類上方。
解釋如果bar
嵌套在foo
則css規則表table.foo td
匹配foo
和bar
表中的tds。 因此,在table.foo td
規則之后聲明了table.bar td
, table.foo td
規則覆蓋了table.bar td
xzyfer的推理是正確的。 一個簡單的解決方法可能是添加
table table.bar td { background-color: green !important; }
假設您的嵌套最多為2個級別,這可以很好地工作,因為它會覆蓋所描述的級聯效果(即,應用的規則不再取決於規則的定義順序)。
工作示例: http : //jsfiddle.net/RQCQS/
如果只希望y影響表foo的直接子代,則需要一些子選擇器。 您可能需要查找thees,因為我知道它們可以用作較舊瀏覽器的解決方法。 另外,我建議將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樣式的影響。 或者,您將必須切換樣式的順序,以便嵌套樣式始終覆蓋外部表樣式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.