CSS Tutorial

Introduction

Edit Template
  • Home
  • /
  • CSS Pseudo-classes

CSS Tutorial

Introduction

Edit Template
  • Home
  • /
  • CSS Pseudo-classes

CSS Pseudo-classes

A pseudo-class lets you style an element based on its state or position, without needing to add a specific class in your HTML. These are super useful for interactions like hovering over a button, clicking a link, or styling the first item in a list.

Basic Syntax:

				
					selector:pseudo-class {
  property: value;
}


				
			

:hover — On Mouse Hover

This applies styles when the user hovers the mouse over an element.

				
					<!DOCTYPE html>
<html lang="en">
<head>
  <style>
    button {
      background-color: steelblue;
      color: white;
      padding: 10px;
      border: none;
    }

    button:hover {
      background-color: darkblue;
      cursor: pointer;
    }
  </style>
</head>
<body>
  <button>Hover Me!</button>
</body>
</html>

				
			

When you move your mouse over the button, its background color changes.

:link — Unvisited Link

Styles an anchor (<a>) before it’s been clicked.

				
					a:link {
  color: blue;
  text-decoration: none;
}

				
			

:visited — After Clicked

Targets a link after it has been visited.

				
					a:visited {
  color: purple;
}

				
			

 Combine it with :link for full control.

:active — While Being Clicked

Used while the element is being clicked.

				
					a:active {
  color: red;
}

				
			

Example:

				
					<!DOCTYPE html>
<html lang="en">
<head>
  <style>
    a:link {
      color: blue;
    }

    a:visited {
      color: purple;
    }

    a:hover {
      color: green;
      text-decoration: underline;
    }

    a:active {
      color: red;
    }
  </style>
</head>
<body>
  <a href="https://learnwitharshyan.com" target="_blank">Visit LearnWithArshyan</a>
</body>
</html>

				
			

:nth-child(n) — Select by Position

Targets elements based on their order.

				
					li:nth-child(2) {
  color: green;
}

				
			

:first-child and :last-child

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

li:last-child {
  font-style: italic;
}

				
			

:focus — When Element is Focused

				
					<!DOCTYPE html>
<html lang="en">
<head>
  <style>
    input:focus {
      border: 2px solid dodgerblue;
      background-color: #f0f8ff;
    }
  </style>
</head>
<body>
  <input type="text" placeholder="Click to focus">
</body>
</html>

				
			

The style is applied only when the user clicks or tabs into the input field.

Summary Table

Pseudo-classDescription
:hoverWhen the mouse hovers over an element
:linkUnvisited link
:visitedLink after it has been clicked
:activeWhile the link or element is being clicked
:focusWhen an input is selected/focused
:nth-child(n)Targets elements by position in a list
:first-childTargets the first child element
:last-childTargets the last child element
Scroll to Top