CSS selectors specify which HTML elements on a web page are targeted for visual styling. Mastering selectors allows for precise design targeting across complex document trees.
CSS supports five main selector categories:
/* 1. Element / Tag Selector */
h1 { color: #f8fafc; }
/* 2. Class Selector (.) */
.btn-primary { background-color: #2563eb; }
/* 3. ID Selector (#) */
#main-header { padding: 1rem; }
/* 4. Attribute Selector ([...]) */
input[type="email"] { border-color: #38bdf8; }
/* 5. Universal Selector (*) */
* { box-sizing: border-box; }
Selector specificity rules:
style="..."): Highest priority (1, 0, 0, 0).#header): High priority (0, 1, 0, 0)..btn, [type="text"], :hover): Medium priority (0, 0, 1, 0).h1, p, div): Low priority (0, 0, 0, 1).flowchart TD
A["Inline Styles (style='...')"] --> B["ID Selectors (#main-id)"]
B --> C["Class, Attribute & Pseudo-Classes (.btn, [type], :hover)"]
C --> D["Element & Pseudo-Elements (h1, p, ::before)"]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CSS Selectors Demonstration</title>
<style>
/* Grouped Element Selectors */
h1, h2, h3 {
font-family: system-ui, sans-serif;
color: #38bdf8;
}
/* Class Selector */
.card-box {
background-color: #1e293b;
padding: 1.5rem;
border-radius: 8px;
}
/* Descendant Class Selector */
.card-box p {
color: #94a3b8;
margin: 0;
}
</style>
</head>
<body style="background-color: #0f172a; color: #f8fafc; padding: 2rem;">
<div class="card-box">
<h2>Targeted Selector Heading</h2>
<p>This paragraph is styled via the descendant selector <code>.card-box p</code>.</p>
</div>
</body>
</html>
.btn) over ID selectors (#btn) for CSS styles: Classes are reusable and keep CSS specificity low and override-friendly.div > body > main > div > p): Deeply nested selector chains make overriding CSS styles difficult later.h1, h2, h3 { font-family: sans-serif; } to reduce code duplication.Write a CSS ruleset targeting all <button> tags with class .btn-danger setting background-color: #ef4444;!
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.
You've completed this section! Take a quick 5-question quiz to check your understanding.