A selector by tag name, like p or h1, changes all of that same tag together. But sometimes you’ll want to “make just this paragraph red” or “make just this button stand out” — that kind of precise aim. That’s where classes come in.
With just a tag name, it becomes “everything”
For example, if you write p, all the paragraphs on the page get the same look.
p {
color: tomato;
}This won’t let you make a fine-grained request like “just this paragraph here.” All or nothing. You’d like to narrow the aim a bit more, right?
Attach a marker, then decorate on target
So you give the tag you want to decorate a marker (a name) with class.
<p class="note">Make just this stand out</p>
<p>A normal paragraph stays the same</p>And in CSS, you target it by putting a . before that name.
.note {
color: tomato;
}Now only the paragraph with class="note" turns red. The other paragraphs stay the same. You’ve hit just the one you wanted.
Run it for real and here’s what happens. Even with the same <p>, only the paragraph with class="note" turns red.
.note turn red. The same class can be used any number of times, all decorated the same way at once.How to decide class names
Names are free — but there are a few tips so you won’t have trouble later.
- Use plain letters, numbers, and hyphens (
-) (likeprofile-card) - Don’t start with a number (
1st-cardis no good,card-1is fine) - Name it by its role, not its look (
warningoverred-text; even if you change the color to blue later, the name won’t become a lie) - Uppercase and lowercase are distinguished (
Noteandnoteare different things; making everything lowercase is the standard)
The third one is an especially important idea. Name a class by “what it is,” not “how you want it to look,” and you’ll get a name that lasts. At first, aiming for “a name whose meaning you’ll understand when you read it later” is enough.
Line up two classes to target just a part inside
Classes aren’t only used one at a time. Line up two with a space, and you can aim in a way that means “that class, inside this one.”
h1 .name {
color: tomato;
}This means “only the part with class="name", inside the h1.” The space between h1 and .name is the signal for “inside of.” It’s handy when you want to color just the name text, not the whole heading.
Run it for real and here’s what happens. The heading text stays as it is, and only the name part wrapped in <span class="name"> gets colored.
.name inside the h1. The surrounding text stays as it is, and just the name part gets colored.Summary of this lesson
- A selector by tag name changes “all of that same tag”
- Attach a marker with
class="name", and you can target it in CSS with.name - The
.(dot) goes on the CSS selector side only - Lining them up with a space, like
h1 .name, targets “that thing inside this one”
