tags:

views:

246

answers:

4

How do I prevent CSS from applying my styles do descendants of descendants without giving them classes or ids? e.g.

#mycontent table {border: 1px solid red;}

Will style the correct table, and then ALL tables inside that one too. All I want is the first table to be selected, not all the subtables.

A: 

Give your table a type (class):

table.mycontent {border: 1px solid red;}

All child tables should not be marked with .mycontent. Then the style will only be applied to the parent table.

User
+3  A: 

You can use the child selector:

#mycontent > table {border: 1px solid red;}

The problem is the child selector isn't supported in IE6. If you need to support that browser you'll have to do something a lot more clunky:

#mycontent table {border: 1px solid red;}
#mycontent table table {border: none;}

Alternatively you can discriminate the tables using classes so you don't get this cascade effect.

cletus
If #document refers to a table, this will not work. If it is a div, then it will.
User
A: 

Why don't you just give that one HTML table tag an id, 'mycontent', and write the CSS as follows:

table#mycontent {
  border: 1px solid red;
}

Andrew Johnson
+3  A: 

What you describe is not the cascade, it is simple selector matching.

There are a few approaches that you could take.

The first is to use a selector that is more specific. If the table you want to style is a child (rather than a grandchilder or other deeper descendent) then you can use a child selector instead of a descendent selector. This is not supported in MSIE 6.

#mycontent > table { border: 1px solid red; }

The second is to add more information to the tables you actually want to style (with an id or class).

#mycontent table.tableThatIWantToStyle {}

The third is to make use of the cascade and style the deeper descendants differently.

#mycontent table { border: 1px solid red; }
#mycontent table table { border: none; }

That said, if you have tables inside tables then the odds are that you are abusing them for layout - which is wrong - and you should fix your markup instead.

David Dorward
I disagree that tables for column layouts are wrong, since with CSS you have to hack it anyhow... so it's just a matter of choosing one's poison.
Antony Carthy
I'll choose the one where I use a presentation tool for presentation and don't claim data relationships that do not exist.
David Dorward
I accept your solution, I was hoping that there was a better way to make cross browser selections, since sometimes one cannot control the HTML sufficiently and needs to control elements indirectly by their position in the DOM.
Antony Carthy