Hover

On a good website, buttons, links and form fields react to what you do: a button gets darker when you point at it, and a field shows that you're typing into it. In this lesson, you'll learn to style these states with Tailwind.

For this lesson, we've prepared the parts of the shelter's website that visitors interact with: Tiger's card with an "Adopt Tiger" button and the Contact section with the opening hours. They're styled with classes from the previous lessons, layout included, but they don't react to anything yet. Later in the lesson, we'll add a contact form and another card.

In the CSS course, you changed the look of an element under the mouse pointer with the pseudo-class :hover:

button:hover {
	background-color: darkorange;
}

In Tailwind, you write the state in front of a class and separate them with a colon:

<button class="bg-orange-500 hover:bg-orange-600">Adopt Tiger</button>

The prefix hover: is called a variant. A class with a variant applies only in its state; the rest of the time, it does nothing. That's why the button keeps both classes: bg-orange-500 is its usual background, and hover:bg-orange-600 a darker one for the moment when the mouse pointer is over it: Adopt Tiger → Adopt Tiger. A variant can go in front of almost any class: hover:text-white, hover:underline, hover:shadow-lg and so on.

Tailwind turns the class into a rule with :hover, just like the ones you wrote yourself. In the selector, the colon from the class name is written as \:, because a plain colon would start a pseudo-class:

.hover\:bg-orange-600:hover {
	background-color: oklch(64.6% 0.222 41.116); /* orange-600 */
}

There's one difference from your own CSS. Phones and tablets have no mouse pointer, and when you tap a button there, some browsers leave its :hover look stuck on it. That's why Tailwind applies hover: classes only on devices that can hover, such as a computer with a mouse. (It puts the rule inside @media (hover: hover); you'll learn about @media in the next lesson, on responsive design.) And as you know from the CSS course, nothing important should be visible only on hover.

Instructions

Add the class hover:bg-orange-600 to the "Adopt Tiger" button. Then run the code, move the mouse pointer over the button and away again.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

1/9