2

I am trying to shorten some css selectors for ease of reading for example:

.a>.c,.b>.c

I thought I had used parenthesis in the past to group the union before continuing with more selectors

(.a,.b)>.c

But it seems this is not valid css.

Did I dream that I have done this before or is there a simple way?

My primary concern is readability of the css rather than number of bytes, however that is another obvious advantage to shortening the selector as above.

1
  • In plain CSS no, parenthesis are not valid. Commented Jun 11, 2013 at 13:47

2 Answers 2

4

Parenthesis aren't used like this in CSS. Please see the Selectors Level 3 W3C Recommendation.

If .c is only ever the child of .a and .b you can simply use:

.c { }

If .a and .b differ from .x (assuming .x has a .c child), you can give them a specific class or data-* attribute:

<div class="a t" <!-- or --> data-t><span class="c"></span></div>
<div class="b t" <!-- or --> data-t><span class="c"></span></div>
<div class="x"><span class="c"></span></div>

And style using:

.t > .c { }
/* Or */
[data-t] > .c { }

Otherwise, there's nothing greatly unreadable about what you already have. If you want to make it even easier to read, simply space it out a little and put each selector on a new line:

.a > .c,
.b > .c {
    ...
}
Sign up to request clarification or add additional context in comments.

2 Comments

thanks for the detailed explaination. The question was probably somewhat over-simplified. In my real-world scenario ".c" is actually "h1". I wanted to avoid adding a class to every h1. In my specific real-world example it's actually quite simple anyway but I can see it coming up again.
In that case you can simply use H1. .a > h1, .b > h1 { }. :-)
0

You can use the :is pseudo selector to shorten selectors which are similar but with different combinations, so each selector inside the :is() is combined with what comes after the :is():

:is(.a, .b) > .c { color: red }
<div class='a'>
  <a class='c'>a > c</a>
</div>
<div class='b'>
  <a class='c'>b > c</a>
</div>
<div class='a'>
  <a class='b'>a > b</a>
</div>
<div class='c'>
  <a class='c'>c > c</a>
</div>

4 Comments

Last time I checked browser support for :is was still limited. Certainly back when this question was asked we didn't have it, but going forward this will definitly be the way to do it.
Support is well established for a few years now. I think this should be the accepted answer nowadays
According to caniuse.com/?search=%3Ais browser support is currently at ~ 92%
You should check browser support according to the users' profile of your app/website. Browser support might be 100% or close then ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.