sass css: target parent class from child

Zeljko picture Zeljko · Feb 15, 2012 · Viewed 108.3k times · Source

I am using sass and found a problem. This is an example of what I am trying to do:

.message-error {
    background-color: red;

    p& {
        background-color: yellow
     }
  }

Expected css:

.message-error {
    background-color: red;
}
p.message-error {
    background-color: yellow ;
}

The idea: all elements with .message-error will be red, except if it is p.message-error. This is not real-life situation, just to show an example.

SASS is not able to compile this, I even tried string concatenation. Is there some plugin that will do exactly the same?

NOTE: I know I can put another css definition like

p.message-error{....}

under, but I would like to avoid that and use one place for all .message-error definitions.

Thanks.

Answer

cimmanon picture cimmanon · Dec 2, 2014

As of Sass 3.4, this is now supported. The syntax looks like this:

.message-error {
    background-color: red;

    @at-root p#{&} {
        background-color: yellow
    }
}

Note the @at-root directive and the interpolation syntax on the ampersand. Failure to include the @at-root directive will result in a selector like .message-error p.message-error rather than p.message-error.