How to make a Sass mixin declare a non-nested selector on base level?

给你一囗甜甜゛ 提交于 2019-12-11 07:18:28

问题


Sorry for the weird language on the question, but I don't know how to describe it any better. I hope this example makes clear what I want:

scss-syntax

.my-smug-selector {
    @include my-smug-mixin(30px);
}

desired css-output

.my-smug-selector{
   // some styles
}

.another-smug-selector-on-base-lvl{
    // some other styles 
}

.smug-non-nested-selector{
    // some other styles 
} 

I'm interested in this in general, but to explain why in the world I would want to do this: I want to have a keyframe-animation defined which gets used by the specified selector, e.g.:

scss-syntax

.my-smug-selector {
    @include my-smug-mixin($vars);
}

desired css-output

.my-smug-selector{
    animation: most-smugish-animation 5s;
}

@keyframes most-smugish-animation {
    from {background:red;}
    to {background:yellow;}
}

回答1:


With Sass 3.3 (which is currently still in development), you could write it like this:

@mixin smugmation() {
    animation: most-smugish-animation 5s;

    @at-root {
        @keyframes most-smugish-animation {
            from {background:red;}
            to {background:yellow;}
        }
    }
}

.my-smug-selector {
    @include smugmation;
}

Otherwise, you'll have to pass the name of the selector as an argument to the mixin:

@mixin smugmation($sel) {
    #{$sel} {
        animation: most-smugish-animation 5s;
    }

    @keyframes most-smugish-animation {
        from {background:red;}
        to {background:yellow;}
    }
}

@include smugmation('.my-smug-selector');


来源:https://stackoverflow.com/questions/21270492/how-to-make-a-sass-mixin-declare-a-non-nested-selector-on-base-level

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