tags:

views:

2294

answers:

5

Is there a way to apply a Class' style to only ONE level of td tags?

<style>.MyClass td {border: solid 1px red;}</style>

<table class="MyClass">
  <tr>
    <td>
      THIS SHOULD HAVE RED BORDERS
    </td>
    <td>
      THIS SHOULD HAVE RED BORDERS
      <table><tr><td>THIS SHOULD NOT HAVE ANY</td></tr></table>
    </td>
  </tr>
</table>
+1  A: 

I guess you could try

table tr td { color: red; }
table tr td table tr td { color: black; }

Or

body table tr td { color: red; }

where 'body' is a selector for your table's parent

But classes are most likely the right way to go here.

Simon Buchan
+12  A: 

Is there a way to apply a Class' style to only ONE level of td tags?

Yes*:

.MyClass>tbody>tr>td { border: solid 1px red; }

But! The ‘>’ direct-child selector does not work in IE6. If you need to support that browser (which you probably do, alas), all you can do is select the inner element separately and un-set the style:

.MyClass td { border: solid 1px red; }
.MyClass td td { border: none; }


*Note that the first example references a tbody element not found in your HTML. It should have been in your HTML, but browsers are generally ok with leaving it out... they just add it in behind the scenes.

bobince
Your first snippet (using the child selector) doesn't appear to work in Firefox 3.0.1. I get a red border around the 'THIS SHOULD NOT HAVE ANY' part.
Nick Presta
This doesn't work in Chrome either
bstoney
your second example is correct, but your first example would put borders on everything. ".MyClass > tr > td" would probably work (in good browsers)
nickf
oop. My fingers done gone wrong. ;-) thanks for the catch, fixed
bobince
Your first snippet doesn't apply _any_ red border in any 'good' browser (Fx 3.0.1, Chrome).
Nick Presta
The phantom TBODY strikes again...
Shog9
I thought it might be that but I wasn't sure. Fixing it to '.MyClass>tbody>tr>td' does indeed work. :-)
Nick Presta
oh FFS. Thanks Shog — I think I need some more sleep. Amazing anyone still voted it up, eh? ;-)
bobince
Hey, it *looks* good...
Simon Buchan
+5  A: 
Nick Presta
Using a class on every single td element may be a little redundant, you'd probably use a class on the containing table element, and then you'd still have to exclude second levels of tables - ie your first example is correct.
thomasrutter
+4  A: 

Just make a selector for tables inside a MyClass.

.MyClass td {border: solid 1px red;}
.MyClass table td {border: none}

(To generically apply to all inner tables, you could also do table table td.)

Chuck
A: 

how about using the CSS :first-child pseudo-class like: .MyClass td:first-child { border: solid 1px red; }

aviko oloo