CSS Syntax Basics
Every CSS rule follows the same basic pattern: a selector pointing at HTML elements, followed by a declaration block of property-value pairs.
selector {
property: value;
property: value;
}
A concrete example:
h1 {
color: #222222;
font-size: 32px;
text-align: center;
}
h1is the selector — it targets every<h1>element.{ }wraps the declaration block.color: #222222;is one declaration:coloris the property,#222222is the value, and the line ends with a semicolon.
A few syntax rules that trip up beginners:
- Every declaration must end with a semicolon
;— omitting it on the last line often still works, but is easy to forget when adding a new line after it, breaking both rules. - Comments use
/* ... */, not//(which is JavaScript syntax). - Property names are always lowercase with hyphens (
font-size, notfontSize— that's the JavaScript equivalent). - Whitespace and indentation don't affect how CSS runs, but consistent formatting makes files far easier to maintain.
Multiple selectors can share one rule by separating them with commas:
h1, h2, h3 {
font-family: Georgia, serif;
}
This avoids repeating the same declarations three times.