CSS Selectors
CSS selectors tell the browser which HTML elements to style. Learn element, class, ID, group, and descendant selectors — the foundation of targeting elements precisely in any webpage.
Types of Selectors
- p { } — Element selector: styles all <p> tags on the page
- .myClass { } — Class selector: styles elements with class='myClass'. Can be reused on multiple elements
- #myId { } — ID selector: styles the single element with id='myId'. Must be unique per page
- * { } — Universal selector: styles every element. Use sparingly (e.g., box-sizing reset)
- h1, h2, p { } — Group selector: apply same styles to multiple elements
- div p { } — Descendant selector: targets <p> inside <div> at any depth
- div > p { } — Child selector: targets only direct child <p> of <div>
Selectors Example
<!DOCTYPE html>
<html>
<head>
<style>
/* Element selector */
p { color: gray; }
/* Class selector */
.highlight { background-color: yellow; font-weight: bold; }
/* ID selector */
#main-title { color: #04AA6D; font-size: 32px; }
/* Group selector */
h2, h3 { color: navy; }
</style>
</head>
<body>
<h1 id="main-title">Welcome</h1>
<h2>Section One</h2>
<p>Normal paragraph text.</p>
<p class="highlight">This paragraph is highlighted!</p>
<h3>Sub-section</h3>
<p>Another paragraph.</p>
</body>
</html>Try It Yourself: Selectors
Tip
Prefer class selectors over IDs for styling. Classes are reusable and have lower specificity, making them easier to manage. Reserve IDs for JavaScript hooks and unique page landmarks. This is the foundation of scalable CSS architecture.
Selectors target HTML elements for styling
Common Mistake
Using the same ID on multiple elements is invalid HTML and causes unpredictable CSS behavior. If you need to apply the same style to multiple elements, always use a class (.highlight) instead of an ID (#highlight).
Practice Task
In the editor above: (1) Add a new class called .underline with text-decoration: underline and color: #E44D26. (2) Apply it to one paragraph using class='underline'. (3) Create a group selector that styles both h1 and #special with the same font-family.
Quick Quiz
Key Takeaways
- CSS selectors tell the browser which HTML elements to style.
- p { } — Element selector: styles all <p> tags on the page
- .myClass { } — Class selector: styles elements with class='myClass'. Can be reused on multiple elements
- #myId { } — ID selector: styles the single element with id='myId'. Must be unique per page