Special Offer Diwali Special Bundle Offer: 3 courses for ₹8,999, save ₹9,001 (50% OFF)! Limited seats available. View Bundles →
0% Completed
Tutorials / CSS Tutorial / Chapter 5: Advanced Selectors, Effects & Variables
CSS ⏱ 10 min read

Pseudo-classes (:hover, :focus, :nth-child)

Pseudo-classes let you style elements based on user interaction states and their structural position in the DOM tree.

What is it?

A pseudo-class is a keyword added to a selector preceded by a colon `:` that specifies a special state of the selected elements.

Why is it used?

Creates interactive hover feedback, active button clicks, form validation styling, and zebra-striped table rows.

Detailed Explanation

Common Pseudo-classes: • User Action: `:hover` (mouse over), `:active` (pressed down), `:focus` / `:focus-visible` (keyboard focus). • Structural: `:first-child`, `:last-child`, `:nth-child(n)` (e.g. `:nth-child(even)` or `:nth-child(2n+1)`). • Form States: `:checked` (checkbox/radio active), `:disabled` (disabled inputs), `:valid` / `:invalid` (input passes constraint).

Syntax Structure

Syntax Blueprint
selector:hover { ... }
selector:focus-visible { ... }
tr:nth-child(even) { ... }

Code Example

CSS Code
/* Interactive Card Elevation */
.tutorial-card {
  background: #ffffff;
  border: 1px solid #eceae4;
  border-radius: 12px;
  padding: 20px;
  transition: transform 0.2s ease, box-shadow 0.2s ease;
}

.tutorial-card:hover {
  transform: translateY(-4px); /* Subtle lift */
  box-shadow: 0 12px 24px rgba(0, 0, 0, 0.08);
  border-color: rgba(28, 28, 28, 0.3);
}

/* Zebra-striping table rows */
table tbody tr:nth-child(even) {
  background-color: #f7f4ed;
}

/* First item highlight */
.lesson-list li:first-child {
  font-weight: 700;
}

Explanation of the Code

• `:hover` creates a tactile, physical lift effect when users point at cards. • `:nth-child(even)` styles alternating rows without adding manual classes in HTML.

Expected Output

Cards gently elevate on cursor hover, and table rows display alternating light parchment zebra striping.

Real-World Application

Used across every modern web interface for interactive buttons, accessible inputs, and readable data tables.

Common Mistakes to Avoid

• Not testing `:hover` states on touchscreens (smartphones don't have mouse hover, so critical features should never be hidden behind hover). • Forgetting `:active` state for tactile button presses.

Quick Practice Challenge

Write a CSS rule that turns every odd list item light gray using `:nth-child(odd)`.

Key Takeaways

• Pseudo-classes target elements based on state or position. • `:hover` and `:active` provide visual micro-interactions. • `:nth-child()` enables programmatic row and column styling.