Here's what i have in my CSS file ...
.search-doctors-box {
position: relative;
z-index: 999;
margin: 0px;
}
.search-doctors-box--at-map {
position: absolute;
margin-bottom: 10px;
top: 0px;
left: 415px;
width: 680px;
}
I want to achieve this in SASS using the & as the parent selector name and to join it with the rest of the string...
.search-doctors-box {
position: relative;
z-index: 999;
margin: 0px;
&--at-map {
position: absolute;
margin-bottom: 10px;
top: 0px;
left: 415px;
width: 680px;
}
}
Is it possible?
Thanks!
SASS Parent Selector Syntax: All you have to do is use & (ampersand) as a prefix followed by some text and when you will compile the SCSS code into CSS code the ampersand sign will be replaced with the name of the parent selector.
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.
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. There are some most commonly used cases: there is a space after the ampersand.
Unfortunately there are limitations to what you can use in combination with the ampersand in selectors - it expects a class name (.
), an id (#
), a pseudo class (:
), or attribute selectors ([]
).
Other acceptable symbols that can also be combined with &
are valid CSS selector combinators ,
>
, +
, and ~
.
You can use string interpolation on the ampersand #{&}
and then you can concatenate it with any string.
However, this way (if you do this in a nested rule) a nested selector still automatically gets the parent selectors attached at the beginning:
.parent {
#{&}--at-map { ... }
}
would return:
.parent .parent--at-map { ... }
But, you can save the contents of the ampersand in a variable and use it outside the parent rule. So in your case something along these lines could work:
$last-rule: null;
.search-doctors-box {
position:relative;
z-index:999;
margin: 0px;
$last-rule: &;
}
#{$last-rule}--at-map {
position: absolute;
margin-bottom:10px;
top: 0px;
left: 415px;
width:680px;
}
or even better, you could use
@at-root
with nested concatenated selectors, like so:
.search-doctors-box {
position:relative;
z-index:999;
margin: 0px;
@at-root #{&}--at-map {
position: absolute;
margin-bottom:10px;
top: 0px;
left: 415px;
width:680px;
}
}
which will give you the desired output:
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