What are Pseudo-classes?

CSS allows us to target elements based on their state. For example, we can target elements that are currently hovered over, or elements that are currently focused. These are called pseudo-classes. By adding it to your selector, you can style elements only if they're in the state you want them to be. We will go over the most common pseudo-classes in this article.

You can target unvisited links by adding the :link pseudo-class to your selector.

CSS
a:link { color: blue; }

This will only apply to unvisited links.

Visited

When you want to target visited links, you can add the :visited pseudo-class to your selector.

CSS
a:visited { color: purple; }

You've seen uses of pseudo-classes throughout your times on the web. A new link on a Google search is blue, but when you have clicked on it before, it is purple.

A Google search for Barack Obama.

Hover

You can apply styles to an element depending on whether or not it is currently being hovered over. Let's say you wanted to change the background color of paragraph tags if they're being hovered over. You can add the :hover pseudo-class to your selector. Let's see an example.

HTML
<!DOCTYPE html> <html> <head> <title>Hover</title> <style> p:hover { background-color: lightgray; } </style> </head> <body> <p>Paragraph</p> <p>Paragraph</p> <p>Paragraph</p> </body> </html>

An example of hover.

Focus

An element is in focus when it is selected or clicked on and/or ready for any kind of input, like a textbox or dropdown. You can target elements that are in focus by adding the :focus pseudo-class to your selector. Let's see an example.

HTML
<!DOCTYPE html> <html> <head> <title>Focus</title> <style> input { margin-bottom: 1rem; } input:focus { background-color: lightgreen; } </style> </head> <body> <div><input type="number" /></div> <div><input type="number" /></div> <div><input type="number" /></div> </body> </html>

An example of focus.

Active

The active state is enabled when the user activates an element, like when a link is currently being clicked on. You can target elements that are in active state by adding the :active pseudo-class to your selector. Let's see an example. Let's see how this works.

HTML
<!DOCTYPE html> <html> <head> <title>Active</title> <style> div { margin: 1rem 0; } a { padding: 0.5rem; } a:active { background-color: lightblue; } </style> </head> <body> <div><a href="https://sabe.io">Link #1</a></div> <div><a href="https://sabe.io">Link #2</a></div> <div><a href="https://sabe.io">Link #3</a></div> </body> </html>

An example of active.

Resources

Next Lesson »
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.