Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid CSS selector applying to more than one level of descendants

Tags:

html

css

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.

like image 787
Antony Carthy Avatar asked Jan 24 '23 14:01

Antony Carthy


2 Answers

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.

like image 54
Quentin Avatar answered Jan 31 '23 20:01

Quentin


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.

like image 43
cletus Avatar answered Jan 31 '23 18:01

cletus