CSS Syntax & Comments
Every CSS rule follows the same simple shape. Learn it once and you can read any stylesheet.
What you will learn
- Read the selector / property / value structure
- Write multiple declarations in one rule
- Add CSS comments
The anatomy of a rule
A CSS rule has a selector (what to style) and a declaration block in { }. Each declaration is a property: value; pair.
h1 {
color: blue;
font-size: 32px;
}h1— the selector: which elements to style.color— the property: what to change.blue— the value: the new setting.- End every declaration with a semicolon
;.
<style>
p {
color: #4338ca;
font-size: 18px;
text-align: center;
}
</style>
<p>One selector, three declarations.</p>One selector (p), three declarations stacked inside the { }. The browser reads them top to bottom and applies all of them to the paragraph: indigo text, 18px size, and centred. You can put as many declarations as you like in one block — each on its own line, each ending in a semicolon. The result is the paragraph you see, coloured, sized and centred all at once.
Watch out: Forgetting the semicolon ; or a closing brace } is the #1 CSS bug. The browser silently ignores the broken rule — so always check your ; and { } first.
Comments
CSS comments sit between /* and */. Use them to label sections or to switch off a rule while testing.
/* Header styles */
h1 { color: teal; }
/* p { color: red; } <- temporarily disabled */Anything between /* and */ is ignored by the browser. The first line is just a label saying “these are header styles” — a note for humans. The last line wraps a real rule in a comment, which switches it off without deleting it. This is the everyday way to test: comment a rule out, see if the problem goes away, then uncomment it.
Q. How do you write a comment in CSS?
✍️ Practice
- Write a rule that gives all
<h2>a colour, a size and centre alignment. - Add comments labelling two sections of your stylesheet.
🏠 Homework
- Deliberately remove a semicolon and a brace to see how the browser reacts, then fix them.