Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SASS CSS: Target Parent Class from Child

Tags:

css

sass

I am using SASS and found an inconvenience. 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.

like image 474
Zeljko Avatar asked Feb 15 '12 12:02

Zeljko


People also ask

How do you target a parent element in Sass?

sass Nesting The parent selector (&)Create a new selector that requires both the parent selector and another on the same element by placing the new selector directly after a parent selector. Have the parent appear after a nested selector in the compiled CSS by placing the parent selector after the nested selector.

How do you target a child to a parent in CSS?

The element>element selector is used to select elements with a specific parent. Note: Elements that are not directly a child of the specified parent, are not selected.

Is there a Sass parent selector?

The parent selector, & , is a special selector invented by Sass that's used in nested selectors to refer to the outer selector. It makes it possible to re-use the outer selector in more complex ways, like adding a pseudo-class or adding a selector before the parent.


1 Answers

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.

like image 57
cimmanon Avatar answered Oct 14 '22 11:10

cimmanon