css - 是否可以将嵌套的 SASS 选择器遍历到父选择器?

标签 css sass

<分区>

只是一个关于 SASS 选择器嵌套的问题,所以我在一个嵌套范围内,我想应用 :hover 伪来使不透明度变为 0,我也想使用这种样式尽管当父标签获取类 is-active 时。现在我会将 is-active 类移到跨度之外并重新应用该样式,但我想知道您能否从嵌套样式中向上移动一个级别,例如遍历?

我的示例 SASS:

.btn-lang {
    // styles...

    > span {
        // styles...

        &:hover { // i want to use this when btn-lang  has class is-active
            opacity: 0;
        }
    }

    // right now I would add these styles here but seems there could be an easier method?
    &.is-active {
        > span {
            &:hover {
                opacity: 0;
            }
        }
    }
}

最佳答案

您想在一个构造中重用两个选择器(.btn-langspan)。这在 SASS 中是不可能的。

这种情况是 extends 真正发挥作用的地方:

// Declaring a reusable extend that will not appear in CSS by itself.
%span-with-hover-on-active-element {
    & > span {
        /* styles for span under btn-lang */ }
    &.is-active > span:hover {
        opacity: 0; } }

.btn-lang {
    /* styles for btn-lang */
    // Apply the span-on-hover thing.
    @extend %span-with-hover-on-active-element; }  

它使复杂的代码可重用且更易于阅读。

生成的 CSS:

.btn-lang > span {
  /* styles for span under btn-lang */
}
.is-active.btn-lang > span:hover {
  opacity: 0;
}

.btn-lang {
  /* styles for btn-lang */
}

关于css - 是否可以将嵌套的 SASS 选择器遍历到父选择器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15975544/

上一篇:javascript font-resizer 在 IE8 或 IE7 中不起作用

下一篇:html - float 和小屏幕的问题

相关文章:

javascript - 将 html anchor 标记值从 javascript 传递到 PHP

css - 如何使用 SASS for 循环生成 CSS 内容

vue.js - Vite如何使用sass

compiler-errors - 嵌套引用父选择器(&)时出现SCSS错误

javascript - 如何通过 CSS 定位特定设备的特定浏览器?

html - anchor 标记不适用于图像悬停效果

css - 如何在 Ionic 中使用 SASS 更改事件按钮文本的颜色?

css - Sass @extend base/default 不扩展伪类?

html - :focus, 后面的链接无法访问移开,div

css - 我如何使用 li :hover to change the WHOLE li color?