简体   繁体   中英

Is it possible to make functions/mixins/shorthands in Sass/SCSS that take selectors as an argument?

Something like this:

@mystery-functionality border-different-when-hover($selector) {
    $selector {
        border: 1px dashed currentColor;
    }
    $selector:hover {
        border: 2px solid currentColor;
    }
}

@use-mystery-functionality border-different-when-hover(nav > abbr);
@use-mystery-functionality border-different-when-hover(a.kebap);
@use-mystery-functionality border-different-when-hover(#bleepable-constructor);

which would compile to this:

nav > abbr {border: 1px dashed currentColor;}
nav > abbr:hover {border: 2px solid currentColor;}
a.kebap {border: 1px dashed currentColor;}
a.kebap:hover {border: 2px solid currentColor;}
#bleepable-constructor {border: 1px dashed currentColor;}
#bleepable-constructor:hover {border: 2px solid currentColor;}

Is that a thing?

Yes, this is possible by using @mixin , escaping the selector inside the mixin and passing the selector into the mixin as a string.

@mixin border-different-when-hover($selector) {
    #{$selector} {
        border: 1px dashed currentColor;
    }
    #{$selector}:hover {
        border: 2px solid currentColor;
    }
}

@include border-different-when-hover('nav > abbr');
@include border-different-when-hover('a.kebap');
@include border-different-when-hover('#bleepable-constructor');

See https://sass-lang.com/documentation/at-rules/mixin#arguments for reference on mixins with arguments.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM