CSS Basics · Lesson 9 of 11

Hover Effects and Transitions

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.2s is 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

  1. Add a .button:hover rule that changes the background-color to #15803d.
  2. In the normal .button rule, add a transition on background-color that lasts 0.2s.
  3. Also give .button the declaration cursor: pointer.
  4. Move the mouse over the button in the preview to try it.
  • There is a .button:hover rule that sets the background to #15803d
  • The button is still #16a34a when the mouse is not over it
  • .button has a 0.2s transition on background-color
  • .button has cursor: pointer