首页 > 解决方案 > SASS/SCSS - 制作一个将“退出”以修改选择器父级的选择器

问题描述

我想在单个代码块中包含选择器的所有相关样式,以便可以轻松引用它。

在我的应用程序中,选择器的有效样式将根据其所在的上下文发生巨大变化。例如,让我们假设这个 CSS:

.container.theme-dark .message
{
    font-size: 16px;
    background-color: black;
    color: white;
}

.container.theme-light .message
{
    font-size: 16px;
    background-color: white;
    color: black;
}

然后,假设我有以下 HTML:

<div>
    <div class="container theme-dark">
        <div class="message">Hello World</div>
    </div>
    <div class="container theme-light">
        <div class="message">Hello World</div>
    </div>
</div>

现在使用 SCSS,我会像这样创建相关的 CSS:

.container
{
    &.theme-dark
    {
        .message
        {
            background-color: black;
            color: white;
        }
    }

    &.theme-light
    {
        .message
        {
            background-color: white;
            color: black;
        }
    }

    .message
    {
        font-size: 16px;
    }
}

我希望能够使用 SCSS 生成该 CSS,并将 .message 元素的所有相关信息放在一个地方。例如(使用一个虚构的 $ 运算符来完成我想要完成的工作):

.container
{
    .message
    {
        font-size: 16px;

        $.theme-light
        {
            background-color: white;
            color: black;
        }

        $.theme-dark
        {
            background-color: black;
            color: white;
        }
    }
}

有任何想法吗?

标签: csssass

解决方案


我想这可能会奏效,就像你说的那样?(如果您将每个示例标记为“理想的 CSS 输出”、“当前的 SCSS、太多的.message块”和“理想的 SCSS 格式”,这将对我有所帮助)

.container
{
    @at-root .message
    {
        font-size: 16px;

        .theme-light &
        {
            background-color: white;
            color: black;
        }

        .theme-dark &
        {
            background-color: black;
            color: white;
        }
    }
}

有了@at-root那里,它会生成.theme-light .message,这对于某些用途来说可能过于宽松,所以不是理想的解决方案......

https://codepen.io/anon/pen/ZMxjEq

基本上&被完整的树路径替换,所以.container .message,没有@at-root,将生成.theme-light .container .message,这不适用于结构。也许还要考虑这一点,这是一个合理的妥协,我会说:

.container
{
    .message
    {
        font-size: 16px;
    }
    @at-root .message
    {
        .theme-dark
        {
            ...
        }

        .theme-light
        {
            ...
        }
    }
}

显然是一种 hacky 解决方案,但显然有效

这个页面也可能有更好的指导


推荐阅读