Code Snippets
/

CSS Selectors Cheat Sheet

CSS Selectors Cheat Sheet

A practical tour of the selectors that cover 90% of real stylesheets: the basics (type, class, id, attribute), combinators for relationships in the DOM tree, the modern pseudo-classes (`:is`, `:where`, `:not`, `:nth-child`), the most common pseudo-elements (`::before`, `::after`, `::placeholder`), and a quick specificity reference so you can predict which rule wins. Skim it once to set the mental model, then come back when a hover style refuses to apply.

CSS
Easy
4 snippets
css-selectors
css-specificity
css-pseudo-classes
css-pseudo-elements

257 views

4

/* Type selector: every <button> on the page. */
button {
    padding: 0.5rem 1rem;
}

/* Class selector: any element with class="primary". */
.primary {
    background: royalblue;
    color: white;
}

/* ID selector: the (unique) element with id="checkout". */
#checkout {
    border: 2px solid limegreen;
}

/* Attribute selectors: presence, exact match, prefix, suffix, substring. */
[data-state] { outline: 1px dashed gray; }       /* has the attribute */
input[type="email"] { border-color: dodgerblue; } /* exact match */
a[href^="https://"] { color: green; }             /* starts with */
img[src$=".svg"] { background: none; }            /* ends with */
link[rel*="icon"] { /* substring match */ }

/* Combinators describe the DOM relationship between two selectors. */
.card p          { line-height: 1.5; }   /* descendant: any p inside .card */
.card > p        { font-weight: 600; }   /* child: direct child only */
h2 + p           { margin-top: 0; }      /* adjacent sibling: p RIGHT after h2 */
h2 ~ p           { color: dimgray; }     /* general sibling: any p after h2 */

These four families (type, class, id, attribute) plus the four combinators are enough to target almost any element you can describe with a single sentence. Attribute selectors are underused: [type="email"] is far more robust than .email-input because it follows the actual semantic of the input rather than a class name that can rot. The descendant combinator is whitespace; the child combinator is >; the adjacent sibling is +; the general sibling is ~. Combinators read left-to-right but the browser actually matches right-to-left, which is why deep selectors are slower; keep them shallow when you can.