Reputation: 755
Let's say I have some HTML like this:
<div id="Group1">
<p class="first">Lorem <span class="special">ipsum</span></p>
<p class="second">Lorem ipsum</p>
<p class="third">Lorem ipsum</p>
</div>
<div id="Group2">
<p class="first">Lorem <span class="special">ipsum</span></p>
<p class="second">Lorem ipsum</p>
<p class="third">Lorem ipsum</p>
</div>
To style the paragraphs differently I must declare my CSS like this:
#Group1 p.first {
color: blue;
}
#Group1 span.special {
color: green;
}
#Group2 p.first {
color: red;
}
#Group2 span.special {
color: orange;
}
Is there a way to group declarations so I don't have to repeat #Group1 and #Group2 (something like this):
#Group1 {
p.first {
color: blue;
}
span.special {
color: green;
}
}
#Group2 {
p.first {
color: red;
}
span.special {
color: orange;
}
}
When you have a lot of selectors, it can get cumbersome to retype always. Is there a way to do this in CSS--it would be a nice shorthand!
Upvotes: 0
Views: 959
Reputation: 179046
CSS preprocessors provide the capability of writing more terse styles that are compiled into CSS.
LESS, Sass, and Stylus are the most popular* as of this writing. Each one has a slightly different set of features, but all of them support selector grouping as you've shown it:
Preprocessor:#Group1 {
p.first {
color: blue;
}
span.special {
color: green;
}
}
Compiled CSS:
#Group1 p.first {
color: blue;
}
#Group1 span.special {
color: green;
}
As far as raw CSS is concerned, there isn't currently any standardized way of grouping selectors in this manner. My recommendation is to try some CSS preprocessors and stick with the one that works best for you. Speaking from my subjective experience, they make maintaining large amounts of CSS in projects significantly easier.
* They're listed alphabetically, not by popularity, which is subject to change
Upvotes: 1