Question

Let's say I have the following:

<div id="container">
    <div id="content">
        <span class="first"></span>
        <span class="second"></span>
    </div>
</div>

And I want to create a CSS rule that affects both .first and .second. I could do the following:

#container #content .first, #container #content .second { font-weight: bold; }

But is there a way to shorten this? Such as:

#container #content .[first|second] { font-weight: bold; }

Of course in this example, I don't save too many characters, but I've had real instances where it'd be helpful to shorten it like this.

So, is something like this possible? I've searched around and couldn't find anything, but I'm hoping that there's some way to accomplish this? An extreme way would be to use something like JavaScript, I guess.

Was it helpful?

Solution 2

Since IDs must be unique, you can simplify it to this:

#content .first, #content .second

CSS3 offers :matches:

#content :matches(.first, .second)

However, as you can see, it's no shorter! Plus it's still new, so older browsers don't support it.

OTHER TIPS

First of all, on it's own there is no way to do something like this in CSS, however there are things called CSS prepocessors which make behavior like this possible. Using a preprocessor like LESS or SASS you would often write something along the lines of

 #container #content{
  /* css specific for this element */
  .first,.second{
   /* css specific for elements with class first or second contained in #container #content
  }
 }

The downside is that you need to either execute javascript on the client side or run the preprocessor every time you change your css on the server side. There are a couple of automated workflows for this, but that's another question.

Since ID's must be unique there is no need to using #container #content.

You could use a "direct child selector":

#content > span

Demo

Why not add another class?

<div id="container">
    <div id="content">
        <span class="first important"></span>
        <span class="second important"></span>
    </div>
</div>

Then use the single selector:

.important { font-weight: bold; }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top