OnlineCBT Logo OnlineCBT
CSS Tutorial
CSS · LESSON 8

Pseudo-Classes for State and Position

By Ratan Updated: 15 Oct 2026

Style elements dynamically on hover, focus, active states, and structural positions like :nth-child().

Level: Beginner to Advanced
Duration: ~60 Mins Deep-Dive

Style interaction and structural state

A pseudo-class selects an element in a particular state or relationship. :hover reacts to pointer hover, :focus-visible provides a keyboard-relevant focus indication, and positional selectors match a node's position among siblings.

.action:hover { background: #1e40af; }
.action:focus-visible {
  outline: 3px solid #f59e0b;
  outline-offset: 3px;
}
input:disabled { opacity: 0.65; }
tbody tr:nth-child(even) { background: #f1f5f9; }
.menu li:first-child { margin-top: 0; }

Use these rules with real button, input and table elements. Hover is not a substitute for keyboard focus, and many touch interactions have no persistent hover state. Do not remove all outlines without providing an equally visible replacement.

Count the right siblings

:nth-child counts element siblings of all types. :nth-of-type counts siblings of the same element type. If a heading precedes two paragraphs, the first paragraph may be the second child but the first paragraph of its type. The formula 2n selects even positions; 2n+1 selects odd positions.

Form state

:checked matches a checked checkbox or radio control. :invalid can match controls failing HTML constraint validation, but showing every empty required input as an error before the user starts can be confusing. Pair validation styling with a clear timing rule and text explaining how to correct the problem.

Keep behavior accessible

If a submenu becomes visible only on hover, keyboard users may be unable to reach it. Design a keyboard-operable control and state model, then use pseudo-classes or explicit state attributes to show that state. CSS alone does not announce validation messages to assistive technology.

Practice

  1. Navigate a button list using Tab and verify that focus is visible.
  2. Stripe a five-row table; rows 2 and 4 should receive the even rule.
  3. Insert an unrelated element among paragraphs and compare nth-child with nth-of-type.
  4. Explain why :disabled styling on a real disabled button differs from merely lowering a normal button's opacity.

हिन्दी संकेत: mouse hover के साथ keyboard focus भी test करें। Position selectors DOM order देखते हैं।

📝 Live Lesson Practice

HTML/CSS JavaScript Python C++ C PHP
⌨️ Practice Inputs (लाइव इनपुट भरें) (खाली होने पर RED, भरने पर GREEN underline)
💻 Code Editor (Monaco VS Code Engine)
👀 Live Preview
Address Contact

+91 7877547686

E-mail

onlinecbtportal@gmail.com

Helpline Number

+91 7877547686


Click To Download
Get it on Google Play

ऐप डाउनलोड करने
के लिए Google Play पर
उपलब्ध है

WhatsApp Chat