A CSS rule-set consists of a selector and a declaration block.
The selector points to the HTML element you want to style, while the declaration block contains one or more declarations separated by semicolons. Each declaration includes a CSS property name and a value, separated by a colon.
The Anatomy of a CSS Rule
selector {
property: value;
property: value;
}
- Selector: Points to the HTML element (e.g.,
h1,p, or.my-class). - Declaration Block: Everything inside the curly braces
{ }. - Property: The type of style you want to change (e.g.,
color,font-size). - Value: The setting you apply to the property (e.g.,
red,16px). - Semicolon ( ; ): Every CSS declaration must end with a semicolon to separate it from the next one.
A Practical Example
Let’s say we want to style all level 1 headings on our page to be blue and centered:
h1 {
color: blue;
text-align: center;
}
In this example:
h1is the selector.coloris the property, andblueis the value.text-alignis the property, andcenteris the value.
CSS Grouping Selectors
If you have several elements that require the same styling, you can group them to keep your code “DRY” (Don’t Repeat Yourself). Use a comma to separate each selector.
Instead of writing:
h1 { text-align: center; color: red; }
h2 { text-align: center; color: red; }
p { text-align: center; color: red; }
You can write:
h1, h2, p {
text-align: center;
color: red;
}
Key Rules to Remember
- Always close curly braces: Every
{must have a matching}. - Use colons for values: Use
:between the property and the value, not=. - Semicolons are mandatory: Forgetting a
;at the end of a line is the most common reason CSS stops working.