HTML & CSSMedium
Types of selectors?
CSS selectors fall into a few families: basic selectors (universal, type, class, ID, attribute), combinators that express relationships (descendant, child, next-sibling, subsequent-sibling), pseudo-classes for state and position (:hover, :nth-child(), :has()), and pseudo-elements that style parts of an element (::before, ::placeholder).
Basic
- Universal
*, typep, class.btn, ID#nav. - Attribute:
[href],[type="text"],[href^="https"](starts with),[href$=".pdf"](ends with),[class*="icon"](contains).
Combinators
- Descendant
nav a: any<a>inside a<nav>. - Child
ul > li: direct children only. - Next sibling
h2 + p: the<p>immediately after an<h2>. - Subsequent sibling
h2 ~ p: all following<p>siblings.
Pseudo-classes (single colon)
- User action:
:hover,:focus,:focus-visible,:active. - Forms:
:checked,:disabled,:required,:invalid,:user-invalid,:placeholder-shown. - Structure:
:first-child,:last-child,:nth-child(2n+1),:nth-of-type(),:empty. - Logical:
:not(),:is(),:where(),:has(). - Other:
:root,:target.
Pseudo-elements (double colon)
::before, ::after (need content), ::first-line, ::first-letter, ::marker, ::placeholder, ::selection, ::backdrop.
Interview tip
Explain the difference clearly: pseudo-classes select elements in a state; pseudo-elements create or target a part of an element.
Code example
html
1<style>2 body { font-family: system-ui; }3 a[href^="https"]::after { content: " ↗"; } /* attribute + pseudo-element */4 a[href$=".pdf"] { color: #b91c1c; }5 ul > li + li { border-top: 1px solid #ddd; } /* child + next sibling */6 h3 ~ p { margin-left: 12px; color: #475569; } /* subsequent siblings */7 li:not(:last-child) { padding-bottom: 4px; }8 input:user-invalid { outline: 2px solid #e11d48; } /* after user interaction */9 label:has(input:checked) { background: #fef9c3; } /* parent selector */10 p::first-letter { font-size: 1.6em; font-weight: 800; }11 ::selection { background: #2b4bff; color: white; }12</style>13<a href="https://developer.mozilla.org">External link</a> · <a href="/guide.pdf">PDF guide</a>14<ul><li>First</li><li>Second</li><li>Third</li></ul>15<h3>Heading</h3>16<p>Sibling paragraph one</p>17<p>Sibling paragraph two</p>18<input type="email" required placeholder="Type an invalid email, then blur">19<label><input type="checkbox"> Highlight me when checked</label>
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the HTML & CSS set.