CSS Syntax
A CSS rule is made of a selector and a declaration block.
selector {
property: value;
property: value;
}
h1 {
color: red;
font-size: 30px;
}
| Part | Meaning | In the example |
|---|---|---|
| Selector | Which HTML element to style | h1 |
| Declaration block | Everything inside curly braces { } | { color: red; font-size: 30px; } |
| Declaration | One property and its value | color: red; |
| Property | What you want to change | color |
| Value | The new setting | red |
Rules to remember
- A property and its value are separated by a colon
:. - Every declaration ends with a semicolon
;. The last one can skip it, but always write it. - Extra spaces and new lines are ignored, so format the code for easy reading.
- Property names are written in lowercase, with hyphens:
background-color.
Group selectors
If many elements share the same style, separate the selectors with a comma.
h1, h2, h3 {
font-family: Arial, sans-serif;
color: #333;
}
Shorthand values
Some properties accept more than one value in one line. This is called a shorthand.
/* long way */
margin-top: 10px;
margin-right: 20px;
margin-bottom: 10px;
margin-left: 20px;
/* shorthand */
margin: 10px 20px;
Read the interview question Why we use shorthand properties in CSS?
Summary
- A rule = selector + declarations in braces.
- A declaration = property: value;
- Group selectors with commas.
- Next: CSS Comments.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |