Every CSS rule follows the same simple pattern. Once you get this, you understand the foundation of all CSS.
Here is the anatomy of a CSS rule:
selector {
property: value;
}
That is it. Three parts. Let me break them down.
The Selector
The selector tells the browser which element to style. It can be an HTML tag name like p or h1, a class like .my-class, an ID like #my-id, or many other things. You point, CSS styles.
The Declaration Block
Inside the curly braces { } is where you put your declarations. Each declaration is a property followed by a colon, then a value, then a semicolon.
The property is what you want to change โ like color, font-size, or background-color. The value is how you want to change it โ like red, 20px, or #f0f0f0.
h1 {
color: blue;
font-size: 32px;
text-align: center;
background-color: yellow;
}
This rule says: find every h1 on the page and make the text blue, 32 pixels tall, centered, with a yellow background.
Important Rules to Remember
- Each declaration ends with a semicolon
; - The last declaration can skip the semicolon, but always including it is a good habit
- Spaces and line breaks do not matter โ you could put everything on one line, but formatting it neatly makes it readable
- CSS ignores anything it does not understand, so a typo will not break your page โ the property just will not apply