Skip to content

Instantly share code, notes, and snippets.

@evanre
Last active March 3, 2018 13:44
Show Gist options
  • Save evanre/64240286a186ce4771cbf3f6a7d1d7be to your computer and use it in GitHub Desktop.
Save evanre/64240286a186ce4771cbf3f6a7d1d7be to your computer and use it in GitHub Desktop.
Sass multi selector inheritance mixin
/// Dependency - str-replace mixin from https://css-tricks.com/snippets/sass/str-replace-function/
/// Replace `$search` with `$replace` in `$string`
/// @author Hugo Giraudel
/// @param {String} $string - Initial string
/// @param {String} $search - Substring to replace
/// @param {String} $replace ('') - New value
/// @return {String} - Updated string
@function str-replace($string, $search, $replace: '') {
$index: str-index($string, $search);
@if $index {
@return str-slice($string, 1, $index - 1) + $replace + str-replace(str-slice($string, $index + str-length($search)), $search, $replace);
}
@return $string;
}
@mixin multi-inherit($this, $mask) {
$selector: ();
@each $amp in $this {
$selector: append($selector, unquote(str-replace($mask, '&', $amp)), comma);
}
@at-root {
#{$selector} {
@content;
}
}
}
// Example that gives:
// - .p1-opened .p1, .p2-opened .p2, .p3-opened .p3 { display: block; }
// instead of:
// .p1-opened .p1, .p2-opened .p1, .p1-opened .p2, .p2-opened .p2 { display: block; }
// playground: https://www.sassmeister.com/
.p1, .p2 {
width: 100%;
@include multi-inherit(&, '&-opened &') {
display: block;
}
&-closed & {
display: none;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment