Web Development - CSS Selectors
CSS Selectors
CSS selectors are patterns used to target the HTML elements you want to style.
Once selected, you apply styles with properties and values.
Basic Selectors
The most common selectors are element, class, and ID.
Example
Element selector:
/* Targets all <p> elements */
p {
color: steelblue;
}
Example
Class selector:
/* Targets elements with class='note' */
.note {
background: #fff8c4;
padding: 8px;
}
Example
ID selector:
/* Targets the element with id='header' */
#header {
text-align: center;
}
Tip: Use classes for reusable styles. IDs should be unique per page.
Grouping Selectors
Grouping lets you style multiple selectors at once by separating them with a comma.
This helps you apply the same style to different elements in a single rule.
Specificity - Which Rule Wins
When multiple rules match, CSS uses specificity to decide which one applies.
- Inline styles: highest
- ID selectors: high
- Class selectors: medium
- Element selectors: low
Example
Specificity in action:
<style>
p { color: black; /* low */
}
.message { color: green; /* medium */
}
#notice { color: orange; /* high */
}
</style>
<p id="notice" class="message">Text</p> <!-- orange wins -->
Try it Yourself »
Tip: Prefer classes over IDs for styling. Reserve IDs for unique anchors and JavaScript hooks.
Best Practices
- Keep selectors short and meaningful.
- Use class selectors for reusable patterns.
- Group selectors that share identical declarations.
You will learn more about advanced selectors in a later chapter.
Tip: For a list of all valid CSS Selectors, go to our CSS Selectors Reference.
Next, you'll learn about CSS Colors - applying color with names, HEX, RGB, and HSL, plus background and text colors.