[css] Apply style to only first level of td tags

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>

This question is related to css css-selectors

The answer is


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.


I wanted to set the width of the first column of the table, and I found this worked (in FF7) - the first column is 50px wide:

#MyTable>thead>tr>th:first-child { width:50px;}

where my markup was

<table id="MyTable">
 <thead>
  <tr>
   <th scope="col">Col1</th>
   <th scope="col">Col2</th>
  </tr>
 </thead>
 <tbody>
   ...
 </tbody>
</table>

This style:

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

gives me:

this http://img12.imageshack.us/img12/4477/borders.png

However, using a class is probably the right approach here.


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


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.


I think, It will work.

.Myclass tr td:first-child{ }

 or 

.Myclass td:first-child { }

how about using the CSS :first-child pseudo-class:

.MyClass td:first-child { border: solid 1px red; }