How to make a Sass mixin declare a non-nested sele

2019-08-02 06:47发布

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;}
}

标签: css sass mixins
1条回答
兄弟一词,经得起流年.
2楼-- · 2019-08-02 07:30

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');
查看更多
登录 后发表回答