How to use before, after and hover in Scss
Scss offers a much cleaner syntax than regular CSS when it comes to complex styling, which means we can call HTML pseudo-elements such as before
and after
in a more readable and efficient way. The same applies to other pseudo-classes such as hover
.
In this tutorial, we will cover how to use before
and after
in Scss and how we can apply the same principle to other CSS selectors.
::before pseudo-class
To access the ::before
pseudo class of an element in Scss we can nest &:before
inside an element class selector. In the below example we are getting ::before
of elements with the class .example
.
.example {
&:before {
content: '';
}
}
::after pseudo-class
::after
can be accessed in exactly the same way. As with ::before
remember that you have to set the content
property to at least an empty string for the pseudo-class to work.
.example {
&:before {
content: '';
}
}
::hover pseudo-class
The same principle applies to the ::hover
selector, let's say we wanted to change the color of all anchor elements on hover. We could do something like this in Scss:
a {
&:hover {
color: orange;
}
}
Other Examples
Basically we can use a nested & selector in Scss to access any pseudo-class available in regular CSS. Another example might be if we wanted to customise the scrollbar of an element that has a fixed height and its overflow set to scroll.
nav {
height: 300px;
width: 300px;
overflow-y: scroll;
&::-webkit-scrollbar {
width: 0.5em;
height: 0.5em;
background: grey;
}
&::-webkit-scrollbar-thumb {
background-color: blue;
border-radius: 3px;
}
}
Conclusion
You now know how to access the before
and after
pseudo-classes using the correct Scss syntax and that the same principle can easily be applied to any pseudo-class.