Before we dive into hover let’s get some foundational knowledge out of the way. What is a pseudo-class?
To start, pseudo-classes are a keyword that follows a selector and appears after a colon (
:). Something like this.
In this case, the pseudo-class is
active. It’s describing the state of a given element. When the element is in that state, the associated styling rules are applied.
There are a number of pseudo-classes, all listed here.
Today, we’re going to talk about a specific pseudo-class,
Let’s start with a button. We’ve styled it to be nice and big and readable.
Now, it’s a great semantic button, but it’s flat. If we go to click it, nothing changes. No visual indication that it’s available to be clicked!
So how can we change that?
This codepen adds a
mouseover event to our button and applies styling in that case.
mouseover works just as it sounds, when a mouse is over the element, the code is triggered. This example also includes a
mouseout event that resets the original styling when the cursor is no longer over the element.
As it turns out, we don’t. We can accomplish the same functionality with a CSS pseudo-class.
This pen is using the
hover is triggered when a user interacts with an element but hasn’t yet activated it. This is nearly identical to the
mouseover functionality we were using before.
Additionally, as long as the
button:hover CSS styling is different than what is defined for a generic button, we don’t need
mouseout at all.
What we did above was not particularly snazzy CSS. We only added a couple of rules to invert the colors of the button that appear on hover. So here is a slightly more fun example of some of the things you can do with hover!
And there you have it. Next time you’re looking to alter an element based on its interactive state, check out some pseudo-classes and see if you can find what you’re looking for there. It’s wonderful to use CSS and HTML where you can! And it’s widely supported!