How to Use the CSS Hover Selector

HeatherCSS0 Comments

Using the CSS Hover Selector

The hover selector is a special type of CSS pseudo-selector. It allows us to use pure CSS to define how a certain element (or multiple elements) will act when we hover over them with the cursor.

Defining which styles are applied to the element when we hover over it is done by creating a special CSS rule in our CSS code. To create these rules, we must append  :hover  to the end of a selector’s name, like so:

To understand how this effect might be used, just think about how hyperlinks generally act when you hover over them on a website (like this one). Have you ever noticed that the text usually either becomes underlined or changes colors when you hover over it? That’s an example of the CSS hover pseudo-selector at work!

Yes of course, a hyperlink gaining an underline is a pretty boring example, but it’s a practical real-world example of how we can use the effect. Luckily for us though, the hover selector can be used to apply styling to any type of HTML element.

Let’s try something a little bit more complicated. Below we’re going to utilize our knowledge of the  :hover selector to create a blue square that will magically transform into an orange rectangle when we hover over it.

I know – so cool.


Go ahead – hover your mouse over that blue square to see our creation in action!

If you look above to the CSS styling rules we’ve created, we’re telling the browser to change both the width and the background color of shapeShifter whenever we hover over it. The styling automatically goes back to default when the cursor is taken off the element, restoring it to its usual blue square.

Unfortunately if you’re on a mobile device, the experience will be slightly different. Until phones can magically detect when we hover our finger over a screen, mobile users are left having to actually click on an element to display it’s hover effect, and again clicking elsewhere to remove it. It’s important to keep this in mind if you’re styling a website for a mobile-first experience.

Experiment with our fancy blue square example here, and see what awesome hover-effects you can come up with! Leave a link to your codepen down below if you create something awesome – you know we all want to see.

Happy coding.

Photo Credit: nickstone333 via Compfight cc modified from original.

Leave a Comment