CSS Pseudo-classes

Pseudo-classes define special element states. Learn how to style hover, focus, and active states.

On this page

CSS Pseudo-classes

A pseudo-class is used to define a special state of an element. It lets you style elements when they are hovered, focused, visited, or based on their position in the HTML structure.

Pseudo-classes start with a colon (:), for example: :hover or :first-child.

Pseudo-classes

Pseudo-classes are commonly used for:

  • Interactive states (hover, focus, active)
  • Link states (link, visited)
  • Form states (checked, disabled)
  • Structural selection (first-child, nth-child)

Interactive Pseudo-classes

Interactive pseudo-classes help create better UI feedback for users.

.button {
  display: inline-block;
  padding: 10px 16px;
  border-radius: 10px;
  border: 1px solid #ddd;
  text-decoration: none;
}

.button:hover {
  border-color: #1f4bd8;
}

.button:active {
  transform: translateY(1px);
}

:focus is important for keyboard accessibility.

input:focus {
  outline: 3px solid #1f4bd8;
  outline-offset: 2px;
}

Link Pseudo-classes

Links have different states that can be styled with pseudo-classes. The recommended order is: link, visited, hover, active.

a:link {
  color: #1f4bd8;
}

a:visited {
  color: #6b4bbd;
}

a:hover {
  text-decoration: underline;
}

a:active {
  opacity: 0.8;
}

Structural Pseudo-classes

Structural pseudo-classes select elements based on their position among siblings.

/* Select the first item */
li:first-child {
  font-weight: bold;
}

/* Select the last item */
li:last-child {
  opacity: 0.8;
}

/* Select every even row */
tr:nth-child(even) {
  background: #fafafa;
}

/* Select every third item */
.tag:nth-child(3n) {
  border-color: #1f4bd8;
}

:nth-child() is very useful for patterns like zebra stripes, grids, and repeated styling.

Code Challenge

Goal: Use pseudo-classes to style interactive and structural states.

HTML:

<ul class="list">
  <li>First</li>
  <li>Second</li>
  <li>Third</li>
  <li>Fourth</li>
</ul>

<a href="#" class="link">Hover me</a>

Task:

  • Make the first list item bold
  • Give every even list item a light background
  • Remove underline from the link and add underline on hover

Try a Solution:

.list {
  padding: 0;
  margin: 0;
  list-style: none;
  max-width: 320px;
}

.list li {
  padding: 10px 12px;
  border: 1px solid #eee;
  border-radius: 10px;
  margin-bottom: 8px;
}

.list li:first-child {
  font-weight: bold;
}

.list li:nth-child(even) {
  background: #fafafa;
}

.link {
  color: #1f4bd8;
  text-decoration: none;
}

.link:hover {
  text-decoration: underline;
}

What’s Next?

Next, you will learn how pseudo-elements allow you to style specific parts of elements.

CSS Pseudo-classes Examples (10)