Comma in CSS, multiple selectors using the same CSS

Viewed 38582
.Resource table.Tbl td
{ /* some css*/ }

.Resource table.Tbl td.num
{ /* some css 2*/ }

.Resource table.Tbl td.num span.icon
{ /* some css 3*/ }

.Resource table.Tbl2 td
{ /* some css*/ }

.Resource table.Tbl2 td.num
{ /* some css 2*/ }

.Resource table.Tbl2 td.num span.icon
{ /* some css 3*/ }

where the CSS for Tbl and Tbl2 should be the same.

.Resource table.Tbl, table.Tbl2 td { /* some css*/ }

doesn't work.

How can I achieve this, without duplicating whole line?

4 Answers

TL;DR: Use the :is() CSS pseudo-class function to fix the precedence of your selector lists.


The problem here is that the syntax for selector lists in CSS treats the comma as having as a very low precedence, below that of combinators (like space) meaning that if you write this:

.Resource table.Tbl, table.Tbl2 td { /* some css*/ }

Then browsers will treat that as equivalent to:

.Resource table.Tbl { /* some css */ }
table.Tbl2 td { /* some css */ }

Which is probably not what you meant.

If instead you want something that's equivalent to:

.Resource table.Tbl td { /* some css */ }
.Resource table.Tbl2 td { /* some css */ }

Then you can express that in CSS using the :is() pseudo-class function:

.Resource :is(table.Tbl, table.Tbl2) td { /* some css*/ }

There's also :where() which is similar, but with a lower specificity.

:is() and :where() are supported in all major browsers, but not in Internet Explorer.

Related