-2

what is the difference between these two scss implementations?

.button {
    :hover{
    }
}

.button {
    &:hover{
    }
}

which one is wrong?

DarkAdvent
  • 33
  • 7
  • Welcome to Stack Overflow. Please see, [What should I do when someone answers my question?](https://stackoverflow.com/help/someone-answers) Also go through the [tour] so that you will be familiar with how to use this platform. – Praveen Kumar Purushothaman Dec 30 '20 at 01:41

2 Answers2

0

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

Imran Rafiq Rather
  • 7,677
  • 1
  • 16
  • 35
  • This does point to a selector. But for that, the ` – Praveen Kumar Purushothaman Dec 29 '20 at 21:42
0

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!.

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252