CSS Pseudo-classes

By Tony 8.31.2024


Think of CSS pseudo-classes as "extensions" of CSS selectors, or a more advanced version of selectors that select an element only when it's in a special state. For example, you can change an element's appearance while being hovered using the :hover pseudo class.

.element:hover {background-color: red;}
.element:active {background-color: green;}
.element:first-child {background-color: blue;}
.element:last-child {background-color: yellow;}
.element:before {
  content: "Before element";
  background-color: gray;
  width: 100px;
}

You might have already noticed the :hover, :active, and :before pseudo classes attached to the element class in the example above. Note that all pseudo classes start with one colon : and is directly attached to the selector without any spaces. The styles defined in the :hover pseudo class only apply to the element when it is being hovered over by the user. The :active styles only apply to the element when it is being clicked. The :first-child psuedo class applies styles to an element only if it is the first child of its parent, and :last-child targets the last child of its parent. The :before pseudo class is a bit different. It basically creates a new element that belongs to the original element, but as a "before" extension. The content property gives the before element actual text content. There's also another pseudo class, :after, which works exactly the same as :before, except it's created after the original element. An element can have both the :before and the :after pseudo classes at the same time.

HTML
CSS
JavaScript
Output

From the example above, you can see that the first element (child) is being highlighted in blue because of the :first-child pseudo class, and the last element is in yellow because of :last-child. Now, when you hover over the other elements, they turn red because of the :hover pseudo class. When you're not hovering over them, they turn back to white because the :hover pseudo class only applies to the element when it is being hovered. Same as the :active pseudo class, the elements only turn green when you click on them. You can also see that each element has a gray "Before element" that appears before them. That's the :before pseudo class at work.

The reason the first child and the last child don't have the :hover and :active effects is because their styles are defined later in the CSS, so it overrides the previous rules. Feel free to play around and explore different pseudo-classes to really learn how they work and how useful they are when creating webpages. From hover effects to applying different styles, pseudo-classes can do them all.