A selector can describe not only which element, but what state it is in. These are called pseudo-classes, and they start with a colon.
The most used one is :hover, which applies while the mouse pointer is over the element:
.button {
background-color: #2563eb;
}
.button:hover {
background-color: #1d4ed8;
}
There is no space between the selector and :hover. The second rule only changes what is different; everything else stays as the first rule set it.
Another useful one is :focus, which applies to the link, button or field that is selected with the keyboard. People who do not use a mouse rely on it to see where they are.
Transitions
Without help, a hover change happens instantly. transition makes the browser animate from the old value to the new one:
.button {
background-color: #2563eb;
transition: background-color 0.2s;
}
- The first value is the property to animate.
- The second is how long it takes:
0.2sis a fifth of a second.
Put the transition on the normal rule, not the :hover rule, so it runs in both directions. Short times, between 0.1 and 0.3 seconds, feel responsive. Longer ones feel slow.
cursor
cursor: pointer turns the mouse arrow into a hand, the usual sign that something can be clicked.
Your Task
- Add a
.button:hoverrule that changes thebackground-colorto#15803d. - In the normal
.buttonrule, add atransitiononbackground-colorthat lasts0.2s. - Also give
.buttonthe declarationcursor: pointer. - Move the mouse over the button in the preview to try it.
- There is a
.button:hoverrule that sets the background to#15803d - The button is still
#16a34awhen the mouse is not over it .buttonhas a0.2stransition onbackground-color.buttonhascursor: pointer