Use the ampersand in SASS to reference specific tags with the parent class?

sass

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>

Best Answer

On Sass 3.4:

.semantic {
    @at-root {
      ul#{&} {
        padding: 0;
        margin: 0;
      }
      p#{&} {
        margin: 0;
      }
    }
}

Generates:

ul.semantic {
  padding: 0;
  margin: 0;
}

p.semantic {
  margin: 0;
}

@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.

Related Topic