CSS Syntax
CSS syntax is the set of rules for writing CSS code. A style rule is a selector followed by a declaration block.
One declaration
A rule for h1 holds one declaration. The declaration sets the color property to blue.
h1 {
color: blue;
}Several declarations
This stylesheet holds three declarations. Each one sits in its own rule and ends with a semicolon.
h1 {
color: blue;
}
p {
color: green;
}
ul {
color: red;
}The later value wins
One rule can set the same property twice. The browser uses the later value.
h1 {
color: red;
color: blue;
}Example
h1 {
color: blue;
}
p {
color: green;
color: red;
}Key points
- Declaration: one property and its value, like color: blue
- A semicolon separates one declaration from the next.
- Write a semicolon after the last declaration too, even though the browser allows it to be left out.
- Extra spaces and line breaks do not change a rule.
- The browser ignores a misspelled property name.
- Property names are case-insensitive, so write them in lowercase.
- A declaration block sits inside curly braces.
In this example, the h1 selector opens a block with one declaration. That declaration sets color to blue. The p block holds two declarations for color. The later value wins, so every paragraph turns red.
Try it Yourself
Edit the code, then press Run.
Runs in your browser โ the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
Which rule is written correctly?