I am having trouble with nesting in Sass. Say I have the following HTML:
<p href="#" class="item">Text</p>
<p href="#" class="item">Text</p>
<a href="#" class="item">Link</a>
When I try to nest my styles in the following I get a compiling error:
.item {
color: black;
a& {
color:blue;
}
}
How do I reference a type selector before the parent selector when it is part of the same element?
For starters, (at time of writing this answer) there's no sass syntax that uses selector&. If you were going to do something like that, you'd need a space between the selector and the ampersand. For example:
The other way of using the ampersand is probably what you're (incorrectly) looking for:
This allows you to extend selectors with other classes, IDs, pseudo-selectors, etc. Unfortunately for your case, this would theoretically compile to something like .itema which obviously doesn't work.
You may just want to rethink how you're writing your CSS. Is there a parent element you could use?
This way, you could easily write your SASS in the following manner:
(Side note: you should take a look at your html. You're mixing single and double quotes AND putting href attributes on p tags.)
AFAIK In case you want to combine ampersand for class and tags at the same time, you need to use this syntax:
will compile to
Other uses (like using the class before
@at-root
or using multiple@at-root
s) will lead to errors.Hope it'll be useful
The
@at-root
-only method will not solve the problem if you intend to extend the closest selector up the chain. As an example:Will compile to:
What if you need to join your tag to
.element
instead of#id
?There's a function in Sass called
selector-unify()
that solves this. Using this with@at-root
it is possible to target.element
.Will compile to:
This feature has landed in the newest version of Sass,
3.3.0.rc.1
(Maptastic Maple)
The two closely related features which you'll need to use are the scriptable
&
, which you can interpolate within a nested styles to reference parent elements, and the@at-root
directive, which places the immediately following selector or block of css at the root (it will not have any parents in the outputted css)See this Github issue for more details
As Kumar points out, this has been possible since Sass
3.3.0.rc.1 (Maptastic Maple)
.We can combine the
@at-root
directive along with interpolation#{}
to arrive at the intended outcome.SASS
Output CSS