Reading history

CSS Pseudo-classes and Pseudo-elements (:hover, :nth-child, ::before)

6 min read Updated 1 views

Learn CSS pseudo-classes such as :hover, :focus-visible, :nth-child and :invalid, and pseudo-elements such as ::before, ::after and ::first-letter.

Ordinary selectors match elements by their tag, class or ID. Pseudo-classes go further and react to what is happening on the page: the link under the mouse, the input with a wrong value, every second row of a table. Pseudo-elements reach inside an element to style just one piece of it, such as its first letter, or to draw a small decoration before or after it. With both, you can often skip adding extra class names to your HTML.

In this lesson you will learn

  • State pseudo-classes: :hover, :focus-visible, :checked
  • Structural pseudo-classes: :nth-child(), :first-child, :not()
  • Form pseudo-classes: :valid, :invalid, :required
  • Pseudo-elements: ::before, ::after, ::first-letter, ::placeholder, ::selection
  • The content property

This lesson extends CSS Selectors.

Pseudo-classes

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Pseudo-classes</title>
  <style>
    body { font-family: sans-serif; margin: 10px; }
    a { color: #1565c0; }
    a:hover { color: #c62828; }
    a:focus-visible { outline: 3px solid #ffb300; }
    table { border-collapse: collapse; width: 100%; margin: 8px 0; }
    td { padding: 4px 8px; }
    tr:nth-child(even) { background: #eceff1; }      /* zebra stripes */
    tr:first-child { font-weight: bold; }
    li:not(:last-child) { border-bottom: 1px solid #ccc; }
    input:invalid { border: 2px solid #c62828; }
    input:valid { border: 2px solid #2e7d32; }
    input:checked + label { font-weight: bold; color: #2e7d32; }
  </style>
</head>
<body>
  <a href="#top">Hover or Tab to this link</a>
  <table>
    <tr><td>Name</td><td>Dept</td></tr><tr><td>Nusrat</td><td>CSE</td></tr>
    <tr><td>Arif</td><td>EEE</td></tr><tr><td>Tania</td><td>CSE</td></tr>
  </table>
  <ul><li>First</li><li>Second</li><li>Last (no border)</li></ul>
  <input type="email" placeholder="type an email" required>
  <input type="checkbox" id="agree"><label for="agree">I agree</label>
</body>
</html>

Result

  • A pseudo-class starts with one colon. a:hover applies while the mouse is over the link.
  • :focus-visible shows an outline when someone reaches the link with the keyboard (press Tab in the result), without showing it on every mouse click. Never remove focus outlines without providing a replacement.
  • tr:nth-child(even) matches the 2nd, 4th, 6th row and so on, creating zebra stripes. nth-child also accepts odd, a number such as 3, or a formula such as 3n+1.
  • li:not(:last-child) adds a border to every item except the last, a neat way to draw separators.
  • input:invalid and input:valid react to HTML validation rules such as required and type="email". Type in the email box to see the border change.
  • input:checked + label styles the label next to a ticked checkbox, combining a pseudo-class with the adjacent sibling selector +.

Pseudo-elements

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Pseudo-elements</title>
  <style>
    body { font-family: sans-serif; margin: 10px; }
    .required::after { content: " *"; color: #c62828; }
    .quote::before { content: "\201C"; font-size: 2em; color: #90a4ae; vertical-align: -0.3em; }
    .ext::after { content: " \2197"; }
    p.intro::first-letter { font-size: 2em; font-weight: bold; color: #00695c; float: left; margin-right: 4px; }
    p.intro::first-line { font-variant: small-caps; }
    ::selection { background: #ffe082; }
    input::placeholder { color: #9e9e9e; font-style: italic; }
    .tag { position: relative; display: inline-block; background: #e3f2fd; padding: 4px 10px; }
    .tag::before { content: ""; position: absolute; left: -8px; top: 0;
                   border: 13px solid transparent; border-right: 8px solid #e3f2fd; border-left: 0; }
  </style>
</head>
<body>
  <label class="required">Email</label> <input placeholder="you@example.com">
  <p class="quote">Code is read more often than it is written.</p>
  <a class="ext" href="#top">External link</a>
  <p class="intro">Pseudo-elements style parts of an element, such as its first letter and first line, without extra HTML. Select some of this text to see the selection colour.</p>
  <span class="tag">CSS-only tag shape</span>
</body>
</html>

Result

  • A pseudo-element uses two colons. ::before and ::after insert generated content as the first or last child of the element, and they only appear if content is set, even to "".
  • .required::after { content: " *"; } adds a red star to required labels; .quote::before adds an opening quotation mark using a Unicode escape.
  • ::first-letter and ::first-line create magazine-style drop caps and small-caps opening lines.
  • ::placeholder styles the hint text inside inputs, and ::selection styles text the user highlights.
  • With content: "" and borders, ::before can draw shapes such as the arrow on the tag, with no images.
  • Generated content is not part of the real text, so screen readers may skip it and users cannot select it. Do not put important information in it.

Quick Reference

SelectorMatches
:hover, :active, :focusMouse over, being clicked, has focus
:first-child, :last-childFirst or last child of its parent
:nth-child(2n), :nth-of-type(3)Children by position
:not(.x)Elements that do not match .x
:disabled, :checked, :invalidForm states
:has(img)Elements that contain a matching element (the “parent selector”)
::before, ::afterGenerated content
::first-letter, ::first-linePart of the text

Common Mistakes

  1. Forgetting content on ::before or ::after, so nothing appears.
  2. Confusing :nth-child with :nth-of-type: the first counts all siblings, the second only those of the same tag.
  3. Adding ::before to images or inputs, which cannot have generated content because they have no children.
  4. Putting the hover style before the transition or on the wrong element, so nothing seems to happen.

Practice Exercises

Exercise 1. Make every third card in a grid have a light yellow background.

Show answer
.card:nth-child(3n) { background: #fff9c4; }

Exercise 2. Add the text “(opens PDF)” after every link whose address ends in .pdf.

Show answer
a[href$=".pdf"]::after { content: " (opens PDF)"; font-size: .85em; }

The attribute selector [href$=".pdf"] matches values ending in “.pdf”.

Frequently Asked Questions

Why do some pseudo-elements use one colon?

Older CSS used a single colon for both kinds, so :before still works. The double colon was introduced to tell pseudo-elements apart from pseudo-classes; use it in new code.

Is :has() supported?

Yes. :has() works in all major browsers since late 2023, letting you style a parent based on its children, for example form:has(input:invalid) button { opacity: .5; }.

Summary

  • Pseudo-classes (:) match states and positions.
  • Pseudo-elements (::) style parts of an element or add generated content.
  • ::before/::after need the content property.
  • Keep essential information in the HTML, not in generated content.

Next: CSS Variables (Custom Properties).

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *