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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With