CSS is written as a set of “which part” and “what to do.” The part that points at “which part” is the selector. First, let’s learn this basic shape as one whole piece, until it’s in your bones.
Let’s look at a real one
p {
color: blue;
}| Part | Role |
|---|---|
p | The selector (points at the paragraphs) |
color | The property (what to change? = the text color) |
blue | The value (how? = to blue) |
So it reads as “make the paragraph text blue.” If you re-read it as “which part { what: how; }” in plain words, it suddenly makes sense.
The result, right here
Here’s what actually running that earlier p { color: blue; } looks like. With that single setting written on p, all the paragraphs turn blue at once.
p the selector, both paragraphs turn blue. Not having to paint them one by one is the joy of selectors.A selector is an HTML tag name
For the “which part” setting, you can use the tag names you learned in HTML as they are. Write p and it’s all paragraphs; write h1 and it’s all the big headings. You can change every tag with the same name, all together in one go.
h1 {
color: red;
}This turns every <h1> on the page red. No need to paint them by hand one by one—this is the joy of CSS.
You can set several things
Inside the { }, you can line up as many lines of settings as you like. One per line, each closed with a ;.
p {
color: blue;
font-size: 18px;
}“Make the paragraph text blue, and a little bigger.” Picture stacking up the things you want to change, top to bottom.
Separate with commas to set them together
“I want both h1 and h2 the same color”—for that, line up the selectors separated with a comma.
h1, h2 {
color: teal;
}This turns both h1 and h2 teal. Since you don’t have to write the same setting twice, there are fewer mistakes too. Read it as “do this to A and B together.”
h1, h2 setting, both the big and middle headings turn teal together. The paragraph, whose name isn’t listed, keeps its original color.When settings collide, the later one wins
What happens if you write different values twice for the same selector?
p {
color: blue;
}
p {
color: red;
}The answer is red. CSS is read top to bottom, and a later setting overwrites an earlier one. When you think “I changed the color but it isn’t working,” it’s a very common trip-up that there was actually another copy of the same selector lower down in the file.
p, the lower one is what stays.Summary of this lesson
- A selector = the marker for which part to change (you can use tag names)
selector { property: value; }is the basic shape- You can line up several settings inside
{ } - Separating with commas, like
h1, h2, lets you set them together
