A CSS file is a list of rules. Every rule follows the same pattern, so once you can read one, you can read all of them.
p {
color: green;
font-size: 18px;
}
The parts of a rule
| Part | In the example | What it does |
|---|---|---|
| Selector | p | Chooses which elements the rule applies to |
| Declaration block | { ... } | Holds the styles for those elements |
| Property | color | The thing you want to change |
| Value | green | What you want it changed to |
| Declaration | color: green; | One property and its value |
A property and its value are joined by a colon :. Each declaration ends with a semicolon ;.
Try it
<style>
p {
color: green;
font-size: 22px;
}
</style>
<p>This paragraph is green and a bit larger.</p>
<p>So is this one. The selector <code>p</code> matches every paragraph.</p>
Comments
Anything between / and / is ignored by the browser. Use comments to leave notes for yourself or to switch a line off while you test.
/* Main heading */
h1 {
color: #d94a00;
/* font-size: 40px; */
}
Formatting is up to you
The browser does not care about line breaks or indentation. These two rules are identical to it:
p { color: green; font-size: 18px; }
p {
color: green;
font-size: 18px;
}
Most people use the second style, one declaration per line, because it is easier to read and easier to change.
Forgetting a semicolon
; between two declarations, the browser can read them as one broken line and skip both. When a style does not apply, check the line above it first.Exercise: write your first rule
Write a rule that makes every h2 blue and 28px in size.
Show a possible solution
h2 {
color: blue;
font-size: 28px;
}