Software Development | CSS Pseudo-Classes

CSS Pseudo-Classes

Overview

CSS pseudo-classes let designers respond to an element's state, such as when a user hovers over it, and change its style using only CSS.

"A pseudo-class is a selector that selects elements that are in a specific state, for example they are the first element of their type, or they are being hovered over by the mouse pointer. They tend to act as if you had applied a class to some part of your document, often helping you cut down on excess classes in your markup, and giving you more flexible, maintainable code." – MDN

Common Pseudo-Classes

Prepare

A common color contrast problem is relying on the browser's default link colors. The :link and :visited pseudo-classes let you set your own.

Activity Instructions

  1. Fork (copy) this CodePen ☼ CSS Pseudo-classes to your own CodePen account.
  2. Add pseudo-class rules that make the links navy in both the unvisited (:link) and visited (:visited) states.
  3. Add a pseudo-class rule that changes links to purple when the user hovers over them.
  4. Add pseudo-class rules that give the "table" (div.datatable) borders so that the borders of the "cells" (div.col elements) do not double up (see the example screenshot below).
  5. Give the last row of the "table" a darker gray background color by using the :last-child pseudo-class.
  6. Define a CSS variable for the border value 1px solid #777 in the :root pseudo-class.
    Hints
    • :root { --bord: _____; } then use it with var(--bord) where needed, for example, border-right: var(--bord);
    • Consider using border-top, border-right, etc. instead of the border shorthand to control exactly which sides get a border.
    • Use the :nth-child() and :last-child pseudo-classes.
Screenshot of the completed pseudo-class CodePen example
Screenshot of the completed pseudo-class CodePen
Solution Example

CodePen ☼ CSS Pseudo-classes example solution.