I have set up a mixin for a button using display:inline-block. I am trying to get to the parent of whatever class that will eventually end up using the mixim, so I can add the font-size: 0px line there to make sure that I don't need to make adjustments to my HTML to avoid unwanted space between each button.
Here's an example... I want the. parent class to receive the font-size: 0px line.
@mixin button() {
display:inline-block;
font-size: 1em;
//other stuff to make a pretty button
&& { font-size: 0px; }
}
.parent{
.child {
@include button();
}
}
The parent selector, & , is a special selector invented by Sass that's used in nested selectors to refer to the outer selector. It makes it possible to re-use the outer selector in more complex ways, like adding a pseudo-class or adding a selector before the parent.
As mentioned in the other answers, you can include mixins in other mixins. In addition, you can scope your mixins. Scoping mixins means that you can have multiple mixins named the same in different scopes without conflicts arising.
Definition and UsageThe element>element selector is used to select elements with a specific parent. Note: Elements that are not directly a child of the specified parent, are not selected.
As of Sass 3.4 this is now possible.
@mixin parent {
@each $selector in & {
$l: length($selector);
@if ($l == 1) {
@error "Used parent mixin on a top-level selector";
} @else {
$parent: nth($selector,1);
@for $i from 2 to $l {
$parent: append($parent,nth($selector,$i));
}
@at-root #{$parent} {
@content;
}
}
}
}
// Use
.grandparent {
.parent{
.child {
font-size: 1em;
@include parent {
font-size: 0px;
}
}
}
}
// Result
.grandparent .parent .child {
font-size: 1em;
}
.grandparent .parent {
font-size: 0px;
}
// Errors:
.root {
@include parent {
content: "Won't work";
}
}
.grandparent .parent, .root {
@include parent {
content: "Also won't work";
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With