June 19, 2025
O. Wolfson
CSS selectors are the foundation of styling web pages. They allow you to target HTML elements precisely so you can apply custom visual styles. In this guide, we'll explore the core types of selectors and how they work—with an interactive React demo to reinforce your learning.
Type any valid CSS selector below to highlight matching elements. You can select by:
• Class: .card, .special
• ID: #header
• Tag: div, li, input
• Attribute: [type=“text”], [data-role=“target”]
• Pseudo-elements: ::before, ::after (visually shown only)
• Combinations: div.card[data-type=“box”]
::before and ::after pseudo-elementsThis element uses ::before and ::after to add decorative arrows. These pseudo-elements are not part of the DOM, so they cannot be selected directly, but their effects are visible.
/* Example CSS applied */
.before-demo::before {
content: " 👉 ";
color: #c71585;
}
.before-demo::after {
content: " 👈 ";
color: #c71585;
}Example: div, p, h1
Targets HTML tags directly.
cssdiv {
background-color: lightblue;
}
🔹 Use this when you want to apply styles to all instances of a tag.
Example: .card, .highlight
css.card {
border: 1px solid #ccc;
padding: 1rem;
}
🔹 Great for reusing styles across multiple elements.
Example: #header, #main-title
css#header {
font-size: 2rem;
color: navy;
}
⚠️ IDs should be unique within a page. Use this for one-off elements.
Example: input[type="text"]
cssinput[type="text"] {
border: 2px solid green;
}
🔹 Perfect for styling based on element attributes—forms, links, etc.
:hover, :nth-child(n), :focuscssdiv:hover {
background-color: #def;
}
li:nth-child(3) {
font-weight: bold;
}
🔹 These respond to user interaction or element position.
::before, ::aftercss.card::before {
content: "👉";
margin-right: 0.5rem;
}
🔹 Use these to insert content or style parts of an element.
When multiple rules apply, specificity determines which style wins:
| Selector Type | Specificity Score |
|---|---|
Element (div) | 0,0,0,1 |
Class (.card) | 0,0,1,0 |
ID (#header) | 0,1,0,0 |
Higher scores win. Inline styles and !important can override even ID rules—but use them sparingly.
Use the React component (included in this demo) to interact with various selectors. Select a rule, and the matching element will highlight. Try hovering, changing inputs, and inspecting the result to build intuition.
Understanding how CSS selectors work—and how to apply them efficiently—makes your stylesheets cleaner, more reusable, and easier to maintain. Practice combining selectors, and don't forget to consider specificity in your decisions.