CSS Selectors Reference
A comprehensive cheat sheet for CSS selectors, combinators, and pseudo-classes.
Basic Selectors
<div>, <p>, <span>...
p matches all <p> elements.
.btn matches <button class="btn">
#header matches <div id="header">
Combinators
div p matches <p> inside a <div>
ul > li matches <li> directly inside <ul>
h1 ~ p matches all <p> after an <h1>
h2 + p matches the first <p> right after <h2>
Attribute Selectors
[disabled] matches <input disabled>
[type="submit"] matches <button type="submit">
[href^="https://"] matches secure links
[src$=".png"] matches PNG images
[class*="grid-"] matches "grid-row" or "my-grid-col"
Pseudo-classes
a:hover styles links on hover
input:focus styles active inputs
li:nth-child(odd) matches 1st, 3rd, 5th items
p:first-child targets the first paragraph
div:not(.active) matches divs without active class
a:has(> img) matches anchor tags containing images
Pseudo-elements
content property.h1::before { content: "★ " }
content property.a::after { content: " ↗" }
::selection { background: #818cf8; }
Understanding CSS Selectors
CSS selectors are the patterns used to select and target HTML elements for styling. They form the foundation of CSS (Cascading Style Sheets). Whether you are looking to style a single unique element on a page or thousands of elements at once, knowing the right selector is essential.
Why Combinators Matter
Combinators allow you to define relationships between selectors. Instead of adding a class to every single element, you can use a descendant (space) or child (>) combinator to target elements based on their position in the DOM. This keeps your HTML clean and your CSS efficient.
Pseudo-classes vs. Pseudo-elements
It's easy to confuse the two:
- Pseudo-classes (starting with a single colon
:) select an element based on its state. For example,:hoverapplies styles when the mouse pointer is over the element, and:first-childtargets an element only if it's the very first element inside its parent. - Pseudo-elements (starting with a double colon
::) target specific parts of an element. For instance,::beforeallows you to insert and style content before the element's actual DOM content.
Optimizing Selector Performance
While modern browsers are incredibly fast, overly complex selectors can still cause rendering bottlenecks on large applications. The browser evaluates selectors from right to left (from the key selector to the ancestors). Therefore, prioritizing classes (like .card) over deeply nested descendant selectors (like div ul li a span) can yield better performance.