what is the difference between these two scss implementations?
.button {
:hover{
}
}
.button {
&:hover{
}
}
which one is wrong?
what is the difference between these two scss implementations?
.button {
:hover{
}
}
.button {
&:hover{
}
}
which one is wrong?
One of the most common uses for &
in Sass is pseudo class selectors
. These include the :hover
, :active
, and :focus
found accompanying selectors like <a>
and <input>
.
In your example, This is the correct syntax in scss
.button {
&:hover{
}
}
And in CSS it is converted to
.button:hover{
}
And the 2nd one, This one is not correct.
.button {
:hover{
}
}
This is converted to:
.button :hover{
}
which is not what we had used it for
The &
is an extremely useful feature in Sass (and Less). It’s used when nesting. It can be a nice time-saver when you know how to use it, or a bit of a time-waster when you’re struggling and could have written the same code in regular CSS.
Let's consider a basic nesting:
.parent {
.child {}
}
This compiles to:
.parent .child {}
The &
comes in handy when you’re nesting and you want to create a more specific selector, like an element that has both of two classes, like this:
.some-class.another-class { }
You can do this while nesting by using the &
.
.some-class {
&.another-class {}
}
The &
in the SCSS is for removing the hierarchy. The space makes a huge difference. The space will make it to look for child element's :hover
state rather than the button
's :hover
state.
In your case, if you have this way:
.button {
:hover{
}
}
.button {
&:hover{
}
}
The output will be:
.button {
}
.button :hover {
}
.button {
}
.button:hover {
}
You can check these out in SassMeister - The Sass Playground!.