SCSS: parent hover selector

风格不统一 提交于 2021-02-16 10:24:16

问题


In scss we can use a parent selector class:

<div class="parent is-active">
  <div class="children"></div>
</div>

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

.children {
  height: 100px;
  width: 100px;

  .is-active & {
    background: red;
  }
}

example

How would you write a parent hover selector?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/37149015/scss-parent-hover-selector

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!