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
- Navigate a button list using Tab and verify that focus is visible.
- Stripe a five-row table; rows 2 and 4 should receive the even rule.
- Insert an unrelated element among paragraphs and compare nth-child with nth-of-type.
- 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 देखते हैं।