views:

306

answers:

3

Say i have a <table> with a css class defined (<table class="x">) and i want to change the 'color' property of just the first level of <td>, is this possible using css without setting classes on the relevant <td>?

I.e.

<table class="x"><tr><td>
  xxxx
   <table><tr><td>yyy</td><tr></table>
</td></tr><table>

I only want the xxxx to change color - so .x td{color:red;} will currently apply to xxxx and yyyy when i only want xxxx targeted, but would rather not give the xxxx td a class name

+9  A: 

Try this:

table.x > tr > td { ... }

The > is the immediate child selector.

Andrew Hare
You learn something new every day -- that's kind of cool...
Andrew Flanagan
I don't think that IE will respond to this...
Ishmael
IE 7 and up support it.
Andrew Hare
FYI this sometimes works in IE7 and doesn't work at all in IE <= 6. http://reference.sitepoint.com/css/childselector
Crescent Fresh
Since IE6 still has a rather large market share, this would not be an ideal solution, since it doesn't work there. The safer solution is to use older css constructs that are supported, since they are more simple, and, well, better supported.
cdeszaq
+7  A: 

One option would be to override the cascade effect by setting the second level to what you want, allowing you to cancel out the effects on the top level.

Something like this:

table.x tr td { ...}

table.x tr td table tr td { ... }

The first statement will apply to all td's under the .x table, but then the second statement will override that for the inner nesting levels (and anything below them). Since it comes after the first statement, it will override anything set in statements above.

This also will work in IE because it uses the more basic construction of ancestors/descendants rather than children, which are not as well supported.

cdeszaq
The second rule overrides the first not because it comes second, but because it is more specific. Check the CSS specs for more information on specificity and the cascade. Also, these selectors can be simplified to `table.x td {…}` and `table.x table td {…}`, respectively.
Ben Blank
@Ben I agree that the specifiers can be simplified, I just put them out in full to better illustrate the point. Also, even though the CSS spec says that specificity is what determines how things get applied, IE doesn't always follow that. In my experience, later stuff is more likely to win out.
cdeszaq
+1  A: 

Note that the > direct child selector is unsupported in IE6, so cdeszaq's method, while more verbose than Andrew Hare's, will still work in hellbrowser.

jongala