my markup is let's say:
<div class="container marker">
<div class="parent">
<div class="child">
content
</div>
</div>
</div>
and my scss would be
.container {
.parent {
.child {
.marker & {
background: red;
}
}
}
}
As long as I put the child styling nested in parent's with the marker class, the ampersand (&) rule doesn't engage. but if i write:
.parent {
.child {
.marker & {
background: red;
}
}
}
everything seems fine. why? what am I missing?
example in CodePen: http://codepen.io/anon/pen/GgRvOV
Ampersand or “&” is a powerful feature of SASS. It enhances the readability of code by using nesting statements, which takes an edge over conventional CSS. We can nest the css class any number of times but most of the times it's not required.
Description. Nesting is combining of different logic structures. Using SASS, we can combine multiple CSS rules within one another. If you are using multiple selectors, then you can use one selector inside another to create compound selectors.
Contents. 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.
The & is a special selector invented by SCSS which is used in nested selectors to refer to the outer selector . It simply means that it will be replaced with the outer selector when compiling to CSS.
Because the output of your sass would be:
.marker .container .parent .child {
background: red;
}
Because you are telling the sass to output .marker &
which is saying this is the parent of this chain, so .container
is being treat as the first child of .marker
.
You need to do:
.parent {
.child {
.container.marker & {
background: red;
}
}
}
Which will output the vanilla CSS:
.container.marker .parent .child {
background: red;
}
A great tool to help you understand how you sass outputs is http://sassmeister.com/
Other alternative is by using variable(s) and SASS’s Interpolation Syntax, using this will keep your original nesting
.container {
$c: &; // store parent into variable
.parent {
.child {
#{$c}.marker & {
background: red;
}
}
}
}
output:
.container.marker .container .parent .child {
background: red;
}
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