This question already has an answer here:
I have a class semantic
which I apply to many different elements. Depending on which html tag the class is applied to, I would like it to apply a different style. This is how I tried to do it:
.semantic {
&ul {
padding: 0;
margin: 0;
}
&p {
margin: 0;
}
}
This doesn't work. Of course I could write it like this, but it wouldn't be very "DRY":
.semantic ul {
padding: 0;
margin: 0;
}
.semantic p {
margin: 0;
}
Is this possible?
Edit: For clarification, here is an example of what my HTML looks like:
<ul class='semantic'>
<li>An Item</li>
</ul>
<p class='semantic'>This text is semantically a paragraph, but should not be displayed as such</p>
Because of how CSS specificity works you could just do this:
In your HTML,
p.semantic
andul.semantic
would havemargin: 0;
and onlyul.semantic
would havepadding: 0;
Less Sass, less CSS. DRY.
If, unlike your example, elements on the real site have even less in common, you might want to rethink why they need to have the same class name.
On Sass 3.4:
Generates:
@at-root moves the block to the top-level. This has several uses (see link) but here it's being used to keep take advantage of the
&
syntax without implying that the rules are child selectors of.semantic
.It's not quite clear what HTML structure you have.
If it's like this:
...then you need classes like
.semantic ul
and.semantic p
. Here's an appropriate SCSS:If HTML structure is like this:
...then you need classes like
.semantic ul
and.semantic p
. You should listen to bookcasey. Here's a sassy version of his DRY suggestion:What you're wanting for would in theory look like this:
This is not possible because the
&
must be first. You're just going to have to deal with the fact that it isn't DRY and write it out by hand:As of Sass 3.3 or 3.4, it is possible using this syntax: