sass - 使用 Sass 将父选择器附加到末尾

标签 sass

好吧,假设我有下面的传统 CSS

.social-media { /* ... */ }
.social-media .twitter { /* ... */ }
.social-media .facebook { /* ... */ }
ul.social-media { /* ... */ }

所以,我试着用 SCSS 这样做:

.social-media {

    /* ... */

    .twitter { 
        /* ... */
    }
    .facebook {
        /* ... */
    }

    // Here's the problem:
    ul& {
        /* ... */
    }
}

最后一部分不起作用,因为和号似乎只应出现在选择器的开头。有解决方法吗?

最佳答案

Sass 3.2 及更早版本

你唯一能做的就是反转你的嵌套或者根本不嵌套: .社交媒体{

    /* ... */

    .twitter { 
        /* ... */
    }
    .facebook {
        /* ... */
    }
}

ul.social-media {
    /* ... */
}

Sass 3.3 及更高版本

您可以使用插值和 @at-root 指令来做到这一点:

.social-media {
    /* ... */

    // Here's the solution:
    @at-root ul#{&} {
        /* ... */
    }
}

但是,如果您的父选择器包含多个选择器,您将需要改用 selector-append:

.social-media, .doodads {
    /* ... */

    // Here's the solution:
    @at-root #{selector-append(ul, &)} {
        /* ... */
    }
}

输出:

.social-media, .doodads {
  /* ... */
}
ul.social-media, ul.doodads {
  /* ... */
}

关于sass - 使用 Sass 将父选择器附加到末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36165213/

相关文章:

css - 在 Rails App hero-unit 中渲染图像

css - 在带有 max() 函数的 SCSS 中使用 env(safe-area-inset-top)

html - Sass::SyntaxError in Static_pages#home - ""之后无效的 CSS:尝试将代码添加到 CSS 文件时出错

angular - 如何通过更改 Angular 5 中的 scss 文件来停止自动重建应用程序?

css - 想让Sass mixin更健壮(字体速记)

CSS 菜单 - 阻止子元素改变父宽度

ruby-on-rails - Rails : Is it possible to reference a instance variable (like @user. color_preferred) 插入字符串?

html - 伪元素 :after changes size of parent div component

angularjs - 弹出的项目不能再使用构建命令

html - 如何在 css 正则表达式中获取 html 数据属性值