DevAcademy
LearnCSSPseudo-classes
IntermediateCSS

Pseudo-classes

Learn how to style elements based on state or position using pseudo-classes like :hover, :focus, and :nth-child.

Reading Time

16 min

Lesson

Lesson 18 of 30

What is a Pseudo-class?

A pseudo-class targets an element in a particular state or position, without needing an extra class or attribute in the HTML. It’s written with a single colon, e.g. :hover.

Interactive States

<style>
  .btn {
    background: steelblue;
    color: white;
    border: none;
    padding: 10px 16px;
    border-radius: 6px;
    cursor: pointer;
  }
  .btn:hover {
    background: #2c5d84;
  }
  .btn:active {
    background: #1f4260;
  }
  .btn:focus {
    outline: 3px solid #ffeaa7;
  }
</style>

<button class="btn">Hover, click, or tab to me</button>
Output

Common State Pseudo-classes

Pseudo-classMatches
:hoverWhen the pointer is over the element
:focusWhen the element has keyboard focus
:activeWhile the element is being clicked/pressed
:disabledA form element that is disabled
:checkedA checked checkbox or radio button
:visitedA link the user has already visited

Structural Pseudo-classes

Structural pseudo-classes select elements based on their position among siblings, without needing to add classes to specific children manually.

Zebra-Striped List with nth-child

<style>
  li {
    padding: 8px;
  }
  li:nth-child(odd) {
    background: #f4f4f4;
  }
  li:first-child {
    font-weight: bold;
  }
  li:last-child {
    color: crimson;
  }
</style>

<ul>
  <li>First item</li>
  <li>Second item</li>
  <li>Third item</li>
  <li>Fourth item</li>
</ul>
Output

Common Structural Pseudo-classes

Pseudo-classMatches
:first-childAn element that is the first child of its parent
:last-childAn element that is the last child of its parent
:nth-child(n)The nth child, supports formulas like 2n or odd/even
:not(selector)Any element that does not match the given selector

Pseudo-classes Need No Extra HTML

The power of pseudo-classes is that they respond to state and structure that already exists — no extra classes, IDs, or JavaScript required to style a hover effect or every other row.

Best Practice

Always style :focus (or focus-visible) on interactive elements, not just :hover — keyboard and screen-reader users rely on visible focus indicators to know where they are on the page.

Interview Questions

Quick Quiz

1. Which pseudo-class matches an element while the pointer is over it?

2. Which pseudo-class selects every other list item for a zebra-stripe effect?

3. Why is styling :focus important, not just :hover?