<h1>SCSS selector mixin (+function)</h2>
<pre>
<span>// Selector map allowing labels as reference</span>
$selector-map: (
'main' : '.main-nav',
'aside' : '.sidebar',
'login' : '.user-account-area'
);
<span>// Function and mixin to return selectors</span>
@function selector($selector-keys...) {
$selector-list: ();
@each $key, $value in $selector-keys {
$selctor-value: map-get($selector-map, $key);
$selector-list: append($selector-list, unquote($selctor-value or $key), comma);
}
@return $selector-list;
}
@mixin selector($selector-keys...) { #{selector($selector-keys...)} { @content;} }
<span>// Use examples:
// Interpolated function call</span>
#{selector(login)} { content: 'A'; }
<span>// Mixin include with passed @content</span>
@include selector(main) { content: 'B'; }
<span>// Pass multiple selectors if you please</span>
@include selector(main, aside) { content: 'C'; }
<span>// Non mapped selectors works too</span>
@include selector('.not-in-map-selector') { content: 'D'; }
<span>// ...So does variables</span>
$selector: 'body > div';
@include selector($selector) { content: 'E'; }
</pre>
<pre>
<span>// Output</span>
.user-account-area { content: 'A'; }
.main-nav { content: 'B'; }
.main-nav, .sidebar { content: 'C'; }
.not-in-map-selector { content: 'D'; }
body > div { content: 'E'; }
</pre>
<p>In response to <a href="https://css-tricks.com/snippets/sass/use-sass-variable-selector" target="_blank">Use a Sass Variable for a Selector</a></p>
// Selector map allowing labels as reference
$selector-map: (
'main' : '.main-nav',
'aside' : '.sidebar',
'login' : '.user-account-area'
);
// Function and mixin to return selectors
@function selector($selector-keys...) {
$selector-list: ();
@each $key, $value in $selector-keys {
$selctor-value: map-get($selector-map, $key);
$selector-list: append($selector-list, unquote($selctor-value or $key), comma);
}
@return $selector-list;
}
@mixin selector($selector-keys...) { #{selector($selector-keys...)} { @content;} }
// Use examples:
// Interpolated function call
#{selector(login)} { content: 'A'; }
// Mixin include with passed @content
@include selector(main) { content: 'B'; }
// Pass multiple selectors if you please
@include selector(main, aside) { content: 'C'; }
// Non mapped selectors works too
@include selector('.not-in-map-selector') { content: 'D'; }
// ...So does variables
$selector: 'body > div';
@include selector($selector) { content: 'E'; }
View Compiled
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.