Shadow Shadow - 3 days ago 4
CSS Question

CSS & Overriding Styles on Nested Elements works only partially

I am wondering about the following code:

<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>


with the following 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;
}


The problem is, when interchanging the classes "foo" and "bar" in the table and its nested table, the style of the td-tags is not correctly set, or at least as not as expected by me. When changing from outer "bar" and inner "foo" to outer "foo" and inner "bar" the colors change as expected, except for the colors of the td-element. What am I doing wrong here, since the other elements of a table change correctly?

I know that using
table table.foo {...}
would work, but this requires to know which style should be used for the inner/nested table and I don't really like this idea. I want to be able to interchange the styles when desired and not include the "inheritance" in the style-sheet... Also dictating the order of the foo or bar styles in the style-sheet is not desirable for me. Please correct me, if this is actually common HTML/CSS practice.

Answer

CSS - Cascading style sheets!

Put simply, if you switch the foo and bar classes in you tables, you'll also need to move the table.foo css rules above the table.bar classes.

Explanation If bar is nested in foo the css rule table.foo td matches both the tds in both the foo and bar tables. So it the table.foo td is declared after the table.bar td rule, the table.foo td rule overwrites the table.bar td

Comments