Using & with pseudo-classes helps you write cleaner styles that change when elements are hovered, focused, or active.
0
0
Combining & with pseudo-classes in SASS
Introduction
You want a button to change color when someone moves their mouse over it.
You want a link to look different when it is clicked or focused by keyboard.
You want to style a form input differently when it is active or disabled.
Syntax
SASS
&:pseudo-class { property: value; }The & symbol means 'this selector' in Sass.
Pseudo-classes like :hover or :focus describe special states of elements.
Examples
This changes the button text color to red when hovered.
SASS
button {
color: blue;
&:hover {
color: red;
}
}This adds an orange outline when the link is focused (like when tabbing with keyboard).
SASS
a {
text-decoration: none;
&:focus {
outline: 2px solid orange;
}
}This styles disabled inputs with a light gray background.
SASS
input {
border: 1px solid gray;
&:disabled {
background-color: lightgray;
}
}Sample Program
This example shows a blue button that gets darker when hovered and shows a bright outline when focused (like when using keyboard navigation).
SASS
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Combining & with Pseudo-classes</title> <style> button { background-color: #007BFF; color: white; border: none; padding: 0.5rem 1rem; font-size: 1rem; border-radius: 0.25rem; cursor: pointer; transition: background-color 0.3s ease; } button:hover { background-color: #0056b3; } button:focus { outline: 3px solid #ffbf47; outline-offset: 2px; } </style> </head> <body> <button>Click me</button> </body> </html>
OutputSuccess
Important Notes
Always use & inside a selector block to refer to the current selector.
Pseudo-classes help improve user experience by showing interactive states.
Test your styles with keyboard navigation to ensure accessibility.
Summary
Use & with pseudo-classes to style element states like hover and focus.
This keeps your Sass code organized and easy to read.
It helps make your website interactive and accessible.