What you'll learn
How to select elements by tag name, by class, and by id.
Why it matters
Styling every <p> the same is rarely what you want. Selectors let you point at exactly the elements you mean.
Explanation
Three selectors cover most of what you need:
- Tag selector:
pselects every paragraph. - Class selector:
.noteselects every element withclass="note". Many elements can share a class. - ID selector:
#titleselects the one element withid="title". An id must be unique on the page.
You can also select several things in one rule by separating them with a comma: h1, h2 { ... }.
When two rules conflict, the more specific selector wins: an id beats a class, and a class beats a tag.
Example
<style>
p {
color: #333;
}
.note {
background: #fff3cd;
padding: 8px;
}
#title {
color: royalblue;
}
</style>
<h1 id="title">Selectors</h1>
<p>A normal paragraph.</p>
<p class="note">A highlighted note.</p>
<p class="note">Another highlighted note.</p>Step-by-step walkthrough
pgives all three paragraphs dark grey text..noteonly matches the two paragraphs withclass="note"and adds a yellow background.#titlematches the single heading withid="title"and colours it blue.- The class name in HTML has no dot (
class="note"), but the selector in CSS does (.note).
Try it yourself
Add a class called big to one paragraph and write a .big rule that sets font-size: 28px.
Classes and idsHTML / CSS
Common mistakes
- Forgetting the dot in a class selector (
noteinstead of.note). - Reusing an id on many elements. Use a class when you need to reuse.
- Spaces in the wrong place.
.a.bmeans one element with both classes..a .bmeans.binside.a. - Fighting specificity with
!important. Prefer simpler, clearer selectors.
Quick quiz
Summary
tag,.classand#idare the core selectors.- Commas group selectors; ids beat classes beat tags in specificity.
- Prefer classes for reusable styles.
Next: colours and fonts.