SCSS: parent hover selector

If I understand your question correctly: https://jsfiddle.net/wx9L9jzj/3/

SCSS:

.parent {
  width: 200px;
  height: 200px;
}

.children {
  height: 100px;
  width: 100px;
  
  .is-active & {
    background: red;
  }
  
  :hover > & {
    background: blue;
  }
}

Note the :hover > & SCSS selector that essentially looks at the parent node to determine if the child was within a :hover pseudo-class. This is not standard CSS and requires the SASS syntax to be compiled to standard CSS, which SASS does by rewriting the selector.

Per SASS documentation on the 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.

When a parent selector is used in an inner selector, it’s replaced with the corresponding outer selector. This happens instead of the normal nesting behavior.


If you want to call another class or pseudo element inside a selector with scss, you have to use the & symbol.

Example:

<div class="class-1 class-2"></div>

SASS

.class-1 {
    &.class-2 {
    }
}

This would compile the following CSS

.class-1.class-2 {
}

To achieve, what you're asking for, you need to do as follows:

.parent {
    &:hover {
        .children {
            // write the desired CSS
        }
    }

    // for the active class you write
    &.is-active {
        .children {
            // desired CSS
        }
    }
}

Working fiddle on hover.

Tags:

Css

Sass