Why can't you group descendants in a CSS selector?
Why isn't there a syntax similar to the following?
#myTable (th,td) {}
Quite simply because nobody bothered to propose a useful syntax... until as recently (relative to the time you posted this anyway) as 2008, as an :any()
pseudo-class. This was discussed in greater depth a little later.
The first implementation surfaced from Mozilla, albeit as late as 2010, in the guise of :-moz-any()
:
#myTable :-moz-any(th, td) {}
The following year, it would be suggested that WebKit follow suit, with :-webkit-any()
:
#myTable :-webkit-any(th, td) {}
But if you were to try to use both prefixes together right now, then due to selector parsing rules you would have to duplicate the rulesets, making your code even longer and defeating the intended purpose of the pseudo-class:
#myTable :-moz-any(th, td) {}
#myTable :-webkit-any(th, td) {}
Which makes using the prefixed selectors in public-facing code all but pointless. I can see no legitimate use for them anywhere other than vendor-specific code, which means you probably won't be using them together, in the same stylesheet.
The new Selectors level 4 working draft has a proposal for a :matches()
pseudo-class, which is based on the original :any()
proposal but may see certain enhancements as the draft is revised:
#myTable :matches(th, td) {}
Of course, since it's a new draft, don't expect browser support until much later.
In the very specific case of styling both th
and td
elements, you could use *
instead assuming that none of the tr
elements in this table will ever contain children other than cell elements, such as script
or template
:
#myTable tr > * {}
But if you're a performance junkie and hate the *
selector, you'll have to stick with doing it the long way.
You can group selectors by using the vendor specific -moz-any()
and -webkit-any()
.
Please see the MDN reference on this, and the W3C recommendation on the :matches()
pseudo-attribute.
Cheers!
You might want to look into SASS - http://sass-lang.com
It allows you to write CSS in a more sensible way (similar to what you suggested), but ti still compiles down to plain old CSS.
For example:
#myTable{
background: #CCC;
tr{
border: 1px solid #EEE;
}
td{
background: blue;
}
}