首页 > 解决方案 > SCSS 嵌套祖先

问题描述

请在我的 SCSS 代码中查看我的评论。

这种更深的嵌套在 SASS 中是可能的吗?我确信我在几年前找到了一个令我满意的解决方案,但我已经忘记了。有人可以帮助阐明我如何进行这种嵌套。

SCSS

.class {
    color: red;

    &__nested {
        color: green;
    }

    &__link {
        color: yellow;

        &:hover {
            border: 1px solid yellow;

            ^^&__nested { // Is something like this one possible?
                color: pink;
            }
        }
    }
}

编译

.class {
    color: red;
}

.class__nested {
    color: green;
}

.class__link {
    color: yellow;
}

.class__link:hover {
    border: 1px solid yellow;
}

.class__link:hover .class__nested { // Is something like this one possible?
    color: pink;
}

我不想这样定义一个变量。

.class {
    $parent: .class;

    &__link {
        color: yellow;

        &:hover {
            border: 1px solid yellow;

            #{$parent}__nested {
                color: pink;
            }
        }
    }
}

标签: csssass

解决方案


你说没有像“.class”这样的变量,但如果你只是想避免强输入它并且没有什么能阻止你实际使用变量,你可以这样做&

.class {
  $self: &;

  color: red;

  &__link {
    color: yellow;
  }

  &__nested {
    color: green;

    &:hover + #{ $self }__link {
      color: pink;
    }  
  }
}

工作示例的 JSFiddle: https ://jsfiddle.net/gy3zLqsm/


推荐阅读