Alex Rivera | Logout

SASS CSS: Target Parent Class from Child

Asked 2012-02-15T12:59:23.160
90

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.

Edit
Report

1 Answer

2

I think if you want to keep them grouped by parent selector, you might need to add a common parent:

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

Of course, body could be replaced with some other common parent, such as #Content or another div name that will contain all the error messages.

UPDATE (Another Idea)

If you leverage @for and lists then it seems like this should work (what I don't know for sure is if the list will allow the . (period).

@for $i from 1 to 3 {
  nth(. p. ul., #{$i})message-error {
    background-color: nth(red yellow cyan, #{$i}));
  }
}

Should compile to something like:

.message-error {
   background-color: red;}
p.message-error {
   background-color: yellow;}
ul.message-error {
   background-color: cyan;}
answered 2012-02-22T16:12:37.023

Your Answer