CSS Syntax and How It Is Applied
Prerequisites: Your first stylesheet
Anatomy of a rule
selector declaration block
┌──┴───┐ ┌───────────┴────────────┐
h1, h2 { color: navy; margin: 0; }
└─┬─┘ └┬─┘
property value
- A selector picks elements; several selectors separated by commas share one block.
- A declaration is
property: value;. Semicolons separate declarations (the last one's is optional, but always write it). - Property names are lowercase by convention; whitespace and line breaks don't matter.
At-rules
Statements starting with @ control how rules apply:
@import url("reset.css");
@media (width >= 60rem) {
body { font-size: 1.125rem; }
}
@font-face {
font-family: "Brand";
src: url("/fonts/brand.woff2") format("woff2");
}
@import must come before other rules, and it loads files one after
another (slow) — prefer several link elements or a build tool.
Errors are silently skipped
CSS was designed to be forward-compatible: a browser that doesn't understand something ignores it and carries on. An invalid declaration is dropped; the rest of the rule still applies.
<!-- Broken on purpose: invalid declarations -->
<style>
p {
color: green;
colour: red;
font-size: 20 px;
margin: 10px
padding: 5px;
font-weight: bold;
}
</style>
<p>Test</p>
<script>
const s = getComputedStyle(document.querySelector("p"));
console.log(s.color, s.fontSize, s.marginTop, s.paddingTop, s.fontWeight);
</script>
rgb(0, 128, 0) 16px 16px 0px 700
colourisn't a property → ignored.20 px(with a space) isn't a valid length → ignored; the default 16 pixels stays.- The missing
;aftermargin: 10pxmerged two lines into one invalid declaration — both margin and padding were lost. colorandfont-weightstill applied.
A validator reports these mistakes:
/* Wrong: three mistakes */
p {
colour: red;
font-size: 20 px;
margin: 10px
padding: 5px;
}
error: CSS: 'colour': Property 'colour' doesn't exist.
error: CSS: 'font-size': Too many values or values are not recognized.
error: CSS: 'margin': Missing a semicolon before the property name 'padding'.
DevTools shows invalid declarations with a strike-through and a warning icon — look there when something "doesn't apply".
How the browser applies CSS
- It parses HTML into the DOM and CSS into the CSSOM.
- For each element it finds every matching rule, and the cascade chooses a value for every property.
- Layout computes sizes and positions; paint draws pixels; composite assembles layers on screen.
Changing some properties (like width) forces layout again; others
(like transform and opacity) only need compositing — which is why
they animate smoothly (Level 2).