Reputation: 211
What is the correct usage of &. in SCSS
In an SCSS file, what is the difference when you are using &. instead of .
.text-field {
.loading {
-----
}
&.error {
------
}
}
Upvotes: 0
Views: 2865
Reputation: 15711
The above answers are good, but limited.
The use can be of other means.
Consider using the ampersand also to qualify context like so:
.child {
.parent &{
}
}
// gives .parent .child
This can also be used multiple times, while not rarely helpful and readable, this is still valid:
.child {
& &{
}
}
// gives .child .child
But can become nice with lists:
.a,.b{
& + &{
}
}
// gives .a + .a, .a + .b, .b + .a, .b + .b
Upvotes: 0
Reputation: 1117
If you use
&.error
The css is compiled as:
.text-field.error
While if you do not use & (as in your loading example) the compiled result is:
.text-field .loading
Which means the in the first example you are expecting the error class on the same 'parent' dom element, while in the latter you expect a child inside which is supposed to have the class loading
.
So, there is no correct usage, it is a matter of what you want to achieve.
Upvotes: 2
Reputation: 629
&
will join whatever follows it to the parent class.
In your example, it means &.error
will evaluate to .text-field.error
- styles that will be applied to any elements with both the text-field
and error
classes.
the .loading
class however will evaluate to .text-field .loading
- so elements with the loading class that have a parent element with the text-field
class.
you can use &
without the .
as well, for example:
.text-field {
&--loading {
// styles
}
}
will evaluate to a single text-field--loading
class.
Upvotes: 4