A CSS rule is made up of two main parts: a selector and a declaration block. Together they tell the browser which HTML elements to style and how to style them.
selector {
property: value;
property: value;
}
| Part | Example | Description |
|---|---|---|
| Selector | h1 |
Points to the HTML element(s) to style |
| Declaration Block | { color: blue; } |
Contains one or more declarations inside curly braces |
| Property | color |
The CSS attribute you want to change |
| Value | blue |
The value assigned to the property |
| Declaration | color: blue; |
A property + value pair, separated by a colon and ending with a semicolon |
This rule makes all <p> elements display with red text and center alignment:
p {
color: red;
text-align: center;
}
You can write multiple declarations inside one rule block. Each declaration must end with a semicolon ;:
h2 {
color: #2e7d52;
font-size: 1.5rem;
font-weight: bold;
margin-bottom: 1rem;
}
You can apply the same styles to multiple selectors by separating them with a comma:
h1, h2, h3 {
color: darkgreen;
font-family: sans-serif;
}
This applies the rule to <h1>, <h2>, and <h3> all at once.
CSS property names and most values are not case-sensitive. However, it is standard practice to write them in lowercase:
/* both are valid, but lowercase is recommended */
P { COLOR: RED; }
p { color: red; }
Comments in CSS start with /* and end with */. They are ignored by the browser and are useful for explaining your code:
/* This rule styles all paragraphs */
p {
color: #333;
line-height: 1.8;
}
/* TODO: add font-size later */
CSS ignores extra whitespace, tabs, and line breaks. These two rules are identical:
/* Expanded (readable) */
p {
color: red;
font-size: 16px;
}
/* Minified (same result) */
p{color:red;font-size:16px;}
Always use the expanded format while writing — it is much easier to read and maintain.