CSS Pseudo-Classes

ADVERTISEMENT

A pseudo-class lets you apply styles to elements based on their state, position, or user interaction — without needing extra classes or JavaScript.

✅ Basic Syntax

selector:pseudo-class {
  /* styles */
}

Example:

a:hover {
  color: red;
}

🧩 Commonly Used Pseudo-Classes

🔹 User Action-Based

Pseudo-ClassDescription
:hoverWhen the user hovers over the element
:focusWhen an element gains focus (e.g., input clicked)
:activeWhile the element is being activated (e.g., clicked)
:visitedA previously visited link
:checkedA checked input (radio/checkbox)
:disabled / :enabledForm elements’ disabled or enabled states
:required / :optionalWhether input is required or not
button:disabled {
  opacity: 0.5;
}
input:focus {
  outline: 2px solid blue;
}

🔹 Structural Pseudo-Classes

These target elements based on their position in the DOM.

Pseudo-ClassDescription
:first-childFirst child of a parent
:last-childLast child of a parent
:nth-child(n)Specific position (1-based index)
:nth-of-type(n)Based on tag type
:only-childOnly child of its parent
ul li:first-child {
  font-weight: bold;
}
ul li:nth-child(odd) {
  background: #f7f7f7;
}

🔹 Negation

input:not([type="submit"]) {
  border: 1px solid #ccc;
}

Targets all inputs except the submit button.

👀 Real-Life Examples

a:hover {
  text-decoration: underline;
}
input:checked + label {
  font-weight: bold;
}
li:nth-child(3) {
  color: red;
}

💡 Tips

  • Combine multiple pseudo-classes:
button:hover:enabled {
  background-color: green;
}
  • Use with :not() to simplify exclusions.
  • :nth-child() uses 1-based indexing.

📦 Bonus: Useful nth-child() Patterns

li:nth-child(odd)   /* 1, 3, 5... */
li:nth-child(even)  /* 2, 4, 6... */
li:nth-child(3n)    /* Every 3rd item */

That’s the power of CSS Pseudo-Classes — letting you style based on interaction and position with zero extra markup.

ADVERTISEMENT