On 21 Sep 2004 09:52:17 -0700,
aj****@blueyonder.co.uk (Andy Fish)
wrote:
I am using descendent selectors to format cells within a table
according to the css class of the table. However, when using nested
tables, it seems to pick up the outer matching rule rather than the
inner one. here's a self-contained example:
<HTML><HEAD>
<style type="text/css">
table.foo td { background-color:red; }
table.bar td { background-color:blue; }
</style>
</HEAD><body>
<table class="bar"><tr><td>
<table class="foo"><tr><td>hello</td></tr></table>
</td></tr></table>
</body></HTML>
The cell containing 'hello' matches both the style rules. Common sense
tells me that 'table.foo' should take precedence because it is the
closest ancestor to the cell in question. however, all the browsers I
tried display the cell in blue i.e. they apply the outer style rule.
Common sense is rarely a good guide when it comes to anything
connected with the WWW. ;-)
Both rules have equal specificty, thus the last one specified in the
stylesheet takes precedence. So the browsers are correct to make the
cells blue.
can anyone tell me how I can achieve my desired result i.e. to have an
inner table with a different style to the outer table, but without
having to specify the class of each individual cell
If foo is always the inner table (i.e. you never have any cases where
bar is inside foo) then simply swapping the order of the style rules
will do the trick.
If foo and bar can contain each other in either combination then a
more complex set of selectors is needed. One possible option would be:
table.foo td, table.bar table.foo td { background-color:red; }
table.bar td, table.foo table.bar td { background-color:blue; }
In this case the inner cells from your HTML example match both
seletors of the first rule and the first selector of the second rule.
Of those three selectors the second selector of the first rule
(table.bar table.foo td) is more specific than the other two and thus
takes precedence.
In theory you could replace descendent selectors with child selectors
table.foo>tr>td { background-color:red; }
table.bar>tr>td { background-color:blue; }
but as IE doesn't support child selectors that's not going to be
practical on the www.
But why are you using nested tables? Surely you're not using tables
for layout? Shocking. ;-)
Steve