Shadow Shadow - 3 months ago 23
CSS Question

CSS & Overriding Styles on Nested Elements works only partially

I am wondering about the following code:

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

with the following CSS:

table {
border-width: 2px;
border-spacing: 2px;
border-style: solid;
} {
border-color: red;
background-color: white;
} td {
background-color: green;
} tr {
background-color: black;
} {
border-color: blue;
background-color: white;
} td {
border-color: black;
background-color: yellow;
} 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 {...}
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.


CSS - Cascading style sheets!

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

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