Reputation: 4956
HTML:
<div class="home">
<div class="a">
A content
</div>
<div class="b">
B content
</div>
<div class="c">
C content
</div>
<div class="d">
D content
</div>
<div class="e">
E content
</div>
</div>
To apply common styles for a,c and e children under home class we can use multiple css selectors as written below.
CSS:
.home .a,.home .c,.home .e{
background-color:#ccc;
}
Question: What is the shorter version of the above css?
Now as a c and e are common children of home. Instead of repeating .home
again and again how can I write a shorter syntax to select class a, b and c that are under home class.
Maybe something like:
.home(.a,.c,.e){
color:#ccc;
}
I know it is wrong but just gives a clear idea about my question here, what I am looking for.
Upvotes: 2
Views: 3711
Reputation: 13536
In current CSS, there is no such syntax.
CSS Selectors 4 has :matches
pseudo-class, that will be able to do such grouping:
.home:matches(.a,.c,.e){
color:#ccc;
}
Unfortunately, it isn't supported by browsers yet. Gecko- and WebKit/Blink-based browsers have experimental implementation of an old draft as :-moz-any()
and -webkit-any()
, respectively, but you will have to write the selectors twice to get it working in these browsers only, so they are far from practical use now.
But you can simplify your CSS like this with CSS preprocessors.
Upvotes: 1
Reputation: 210
If you want to mention names of classes explicitly (e.g. a, b, c
) but don't want repetition in your source css, maybe it's nice idea to start using some CSS-preprocessor, like Sass or less. For example, with Sass you can write in .scss file this:
.home {
.a, .c, .e {
background-color:#ccc;
}
}
On the output Sass will compile it to .css file:
.home .a, .home .c, .home .e{
background-color:#ccc;
}
This will keep your source files clean.
Upvotes: 1
Reputation: 123387
div
with class a
, c
and e
can be selected using :nth-child
pseudoclass
.home > div:nth-child(2n + 1) {
background-color:#ccc;
}
with the given markup this is equivalent to
.home .a, .home .c, .home .e{
background-color:#ccc;
}
Codepen Example: http://codepen.io/anon/pen/XbPNPw
Upvotes: 1
Reputation: 18123
The code .home(.a,.c,.e)
won't work, and there is no OR
operator for CSS selectors. home .a,.home .c,.home .e
is the shortest way.
But here a few selectors that might help you:
.home div { } /* all divs in home */
.home > div { } /* all divs that are a direct child of .home */
.home * { } /* all elements in .home */
.home > * { } /* all direct children of .home */
There also exist CSS preprocessors, like SASS and LESS that give you more possibilities.
Upvotes: 7