CSS Syntax: Rules, Declarations, Comments, and How Browsers Handle Errors
The structure of CSS: rules, selectors, declarations, values and at-rules, whitespace, comments and case sensitivity, vendor prefixes, and the precise way browsers recover from errors, which is what makes fallbacks and progressive enhancement possible.
kvi5hnuCode Sprout team member12 min readOn this page
A stylesheet is a list of rules, and each rule is a selector plus a block of declarations. The grammar is small, but the details matter: which characters are allowed, what's case-sensitive, and above all what a browser does when it meets something it doesn't understand. CSS was designed so that a browser skips what it can't parse and keeps going. That one decision is why new CSS features can be adopted gradually, and why a typo never breaks the rest of your page.
Anatomy of a rule
.book-card h2 {
color: #8a3b12;
font-size: 1.25rem;
}
| Part | In the example | What it is |
|---|---|---|
| rule (or ruleset) | the whole thing | a selector and its declaration block |
| selector | .book-card h2 | which elements the rule applies to |
| declaration block | { ... } | the declarations, between braces |
| declaration | color: #8a3b12; | one property and its value |
| property | color | what to change |
| value | #8a3b12 | what to change it to |
- Declarations are separated by semicolons. The semicolon after the last declaration is optional, but always write it: adding another declaration later without it breaks both.
- A value can contain several parts, separated by spaces, commas or slashes, depending on the property:
margin: 0 auto,font-family: Georgia, serif,grid-area: 1 / 2 / 3 / 4,font: italic 1rem/1.5 Georgia, serif. - Keywords are not quoted.
color: reduses the keywordred. Quoting it, as incolor: "red", makes it a string, whichcolordoesn't accept, so the declaration is ignored. - A selector list (sometimes called grouping) applies one block to several selectors:
h1, h2, h3 { line-height: 1.2; }.
At-rules
Statements that begin with @ are at-rules. They aren't styles for elements: they tell the browser how to process the stylesheet or when rules apply. Some end with a semicolon, others contain a block:
@import url("reset.css"); /* statement */
@layer reset, components; /* statement */
@media (width >= 40em) { /* block containing rules */
.book-grid { grid-template-columns: repeat(3, 1fr); }
}
@font-face { /* block containing descriptors */
font-family: "Harbor Serif";
src: url("/fonts/harbor-serif.woff2") format("woff2");
}
Inside @font-face, @property and @counter-style, the name: value pairs are descriptors, not properties. (@page accepts both: descriptors such as size, and ordinary properties such as margin.) They look the same but belong to the at-rule: src is valid in @font-face and meaningless in an ordinary rule. Article 121 lists every at-rule.
Whitespace and case
Whitespace (spaces, tabs and newlines) is mostly ignored between tokens, so these are the same rule:
.price{color:#2f7d4f;font-weight:700}
.price {
color: #2f7d4f;
font-weight: 700;
}
Whitespace does matter in a few places:
- In selectors, a space is the descendant combinator.
.card h2means "anh2inside.card", while.card.featured(no space) means "an element with both classes". Article 9 covers combinators. - Inside
calc(),+and-need spaces around them:calc(100% - 2rem)works, butcalc(100%-2rem)is invalid, because-2remreads as a negative number. - Between a number and its unit there's no space:
2rem, never2 rem.
Case sensitivity depends on what you're writing:
| Case-insensitive | Case-sensitive |
|---|---|
property names (COLOR works) | class names and IDs (.Card doesn't match class="card") |
keywords (RED, Block) | custom property names (--Gap and --gap are different) |
units (10PX), hex colors (#FFF) | names you define: @keyframes, @layer, grid line and area, container and counter names |
HTML element names in selectors (DIV) | values of attributes you define, such as class, title and data-*, unless you add i (article 8) |
font family names ("georgia" finds Georgia) | strings, and URLs as far as the server treats them |
values of HTML's keyword attributes, such as [type="TEXT"] |
Lowercase everything you can. It's the universal convention, and you'll never have to remember the table.

Each pair differs by one space or one capital letter, and the result changes completely.
Comments
CSS has one comment syntax, /* ... */, which can span lines:
/* Book cards on the home page */
.book-card {
padding: 1rem; /* matches the grid gap */
}
- Comments can't be nested. In
/* a /* b */ c */, the first*/ends the comment, soc */is left as broken CSS. - There are no
//line comments.// noteis not a comment: the browser reads it as the start of a selector or declaration, and drops whatever it swallows, often the next rule. This is a common bug when people copy code from Sass, which does allow//comments. - HTML comments
<!--and-->inside a stylesheet are ignored for historical reasons, but don't use them.
// Highlight the shop name
h1 { color: #8a3b12; }
p { color: #2f7d4f; }
Change // to /* */ around the comment, and the heading turns brown.
Vendor prefixes
When browsers implemented features before the specification was stable, they used vendor prefixes: -webkit- (Safari, and Chromium for compatibility), -moz- (Firefox), and historically -ms- and -o-. You'll see them in older code:
.legacy {
-webkit-transition: opacity 0.3s;
transition: opacity 0.3s; /* unprefixed version last, so it wins */
}
Today, browsers ship new features unprefixed, often behind a flag first, so you rarely need prefixes. A few remain useful:
-webkit-background-clip: textis still needed by some browser versions alongsidebackground-clip: text(article 48).-webkit-line-clampwithdisplay: -webkit-boxis still the reliable way to clamp text to a number of lines (article 43).- Some pseudo-elements, such as
::-webkit-scrollbar, exist only with a prefix.
If you support old browsers, let a build tool such as Autoprefixer or Lightning CSS add prefixes from your browser targets, instead of writing them by hand (article 120).
How browsers handle errors
The CSS specifications define exactly what to do with invalid CSS, and every browser follows them. The general rule is to ignore the smallest piece that doesn't make sense and continue.
An invalid declaration is dropped on its own
If a property name is unknown, or the value isn't valid for that property, that one declaration is ignored. The rest of the block still applies:
.notice {
colr: white; /* unknown property: ignored */
background: #8a3b12;
padding: 1rem 1.5rem;
border-radius: big; /* invalid value: ignored */
color: white;
}
The notice is brown with white text and padding, but square, because border-radius: big was ignored.
Fallbacks rely on this
Because unknown values are dropped, you can write a fallback first and a newer value after it. A browser that understands the second declaration uses it; one that doesn't keeps the first:
.panel {
background: #6a4ad8; /* every browser */
background: oklch(55% 0.2 290); /* browsers that support oklch() */
height: 100vh; /* fallback */
height: 100dvh; /* dynamic viewport height */
}
Later declarations win only if they're valid, so the order is always fallback first, then the modern value. Article 6 builds on this.
An invalid selector drops the whole rule
A selector list is all or nothing. If any selector in the list is invalid or unsupported, the browser ignores the whole rule, including the valid selectors:
h2, .sale:hoover { /* :hoover doesn't exist */
color: #8a3b12;
}
h3, .sale:hover {
color: #2f7d4f;
}
That's why, when you use a new pseudo-class, you shouldn't group it with other selectors. Put it in its own rule. The exception is the forgiving selector lists inside :is() and :where(), which skip invalid selectors and keep the rest (article 12).
Unknown at-rules and blocks are skipped
An at-rule the browser doesn't recognize is skipped up to its end: the next semicolon, or the matching closing brace of its block. Everything after it is parsed normally. An @media or @supports block whose condition is false keeps its rules, but they don't apply.
Braces, quotes and parentheses must balance
The parser keeps track of {}, (), [] and quotes even inside parts it's skipping, so a skipped section ends at the right place. A missing closing brace is the most damaging error: everything after it becomes part of the unclosed block, as nested rules that no longer match what they should, so rules further down the file seem to stop working. If a whole section of a stylesheet is ignored, look for an unclosed { or an unclosed string just above it.
h1 { color: #8a3b12;
p { color: #2f7d4f; }
.tag { background: gold; }
Here the heading is brown, but the paragraphs aren't green or gold: the browser treated the following rules as part of the h1 block. Since browsers support nesting (article 21), they become nested rules, h1 p and h1 .tag, which match only elements inside the h1, and there are none. Add the missing } after the first declaration to fix it.
Valid syntax, invalid at computed-value time
One kind of error can't be caught while parsing. A declaration containing var() is accepted as long as its syntax is plausible, because the browser can't know the variable's value yet:
:root { --accent: 12px; }
.badge { color: var(--accent); } /* parses fine; 12px isn't a color */
When the browser computes the style and finds that 12px isn't a color, the declaration becomes invalid at computed-value time. It's not dropped in favor of an earlier color declaration: it behaves as unset, so color is inherited from the parent. Article 27 covers this in detail.

Compare the two bottom panels: a value that's invalid while parsing leaves the earlier declaration in place, but a var() that turns out invalid replaces it and falls back to inheritance.
Escapes and @charset
- Escapes: a backslash introduces a character by its hexadecimal code point, as in
content: "\2014"for an em dash, or escapes a special character in a selector, as in.\31 0colfor a class named10col. Modern stylesheets are UTF-8, so you can type most characters directly:content: "—". @charset "UTF-8";declares a stylesheet's encoding. It must be the very first thing in the file, with exactly that spacing. Browsers assume UTF-8 when the server says so or the page is UTF-8, so@charsetis rarely needed today.
What's current
//comments are still invalid in plain CSS, even in browsers that support nesting.- Nested rules (article 21) changed some error recovery: a selector-like line inside a declaration block is now parsed as a nested rule instead of being skipped as a bad declaration.
- New features ship unprefixed. Browser vendors have mostly stopped shipping new prefixed properties, and use flags and origin trials for experiments instead.
Common questions
One of my rules doesn't work. Is the whole stylesheet broken?
Almost never. Browsers drop only the broken part: an invalid declaration, or the rule whose selector is invalid. If everything after a certain point stops working, look for a missing } or an unclosed quote just above it. DevTools shows ignored declarations struck through with a warning icon (article 4).
Is the semicolon after the last declaration required? No, but write it anyway. Without it, the next declaration you add, or one moved there in a merge, joins the previous value and both become invalid.
Are class names case-sensitive?
Yes. .featured doesn't match class="Featured". Property names, keywords and units are case-insensitive, but conventions use lowercase for all of them.
Why does color: "red" not work?
Quotes make a string. color accepts color keywords and functions, not strings, so the declaration is invalid and ignored. Quote only values that are strings: content, font family names with spaces, quotes, and grid area templates.
Do I still need vendor prefixes?
Rarely. Check a compatibility table before adding one, and let a build tool handle them if you support old browsers. -webkit-line-clamp and -webkit-background-clip: text are the common exceptions.
Why did grouping two selectors break a rule that worked on its own?
Selector lists are all or nothing: if one selector is invalid in a browser, such as a pseudo-class that browser doesn't support, the whole rule is dropped. Write the new selector in a separate rule, or wrap the list in :is(), which forgives invalid selectors.
Summary
- A rule is a selector and a declaration block, and each declaration is a property, a colon, a value and a semicolon.
- At-rules start with
@. Some are statements ending in a semicolon, and others contain rules or descriptors. - Whitespace is mostly free, except in selectors, around
+and-incalc(), and between numbers and units. - Property names and keywords are case-insensitive. Class names, IDs and custom property names are case-sensitive.
- Comments use
/* */only. They don't nest, and//isn't a comment. - Browsers drop an invalid declaration on its own, an entire rule if a selector in its list is invalid, and unknown at-rules up to their end, then carry on.
- That error handling enables fallbacks: write the safe value first and the modern value after it.
- A missing brace makes the following rules part of the unclosed block, and
var()errors appear only at computed-value time.
Practice questions
Which declarations in this rule apply?
.cover {
width: 12rem;
height: 18 rem;
border: 1px solid #ccc;
background-color: "white";
}
Answer
width and border. height: 18 rem is invalid because of the space between the number and the unit. background-color: "white" is invalid because a string isn't a color. Each invalid declaration is dropped on its own, so the other two still apply.
Why is the .sale link not green?
a:hover, a:fokus-visible, .sale { color: green; }
Answer
:fokus-visible is misspelled, so it's an invalid selector, and an invalid selector anywhere in a list makes the browser ignore the entire rule, including a:hover and .sale. Fix the typo, or split the selectors into separate rules.
A teammate writes this to use oklch() with a fallback. What's wrong?
.badge {
background: oklch(70% 0.15 150);
background: #4caf7a;
}
Answer
The order is reversed. Both declarations are valid in modern browsers, so the later one, the hex fallback, always wins, and oklch() is never used. Put the fallback first and the modern value second.
After you add a new rule near the top of a stylesheet, every rule below it stops working. What's the most likely cause?
Answer
An unclosed {, or an unclosed string, in the new rule. The parser treats everything after it as part of that block, so the following rules aren't seen as separate rules. Find the missing } or quote.
What does this comment do?
/* Header styles /* TODO: dark theme */ */
header { background: #f4efe6; }
Answer
Comments don't nest. The first */ ends the comment, which leaves a stray */ before header. The browser reads */ header as part of the selector, which is invalid, so the header rule is dropped. Remove the inner comment markers.
Previous: Adding CSS to a Page: link, style, @import and Inline Styles
Next: Using Browser DevTools for CSS: Inspecting, Computed Styles and Live Editing

More in CSS Course
Quiz: CSS Delicate Details
Twenty-five questions on the edge cases that surprise experienced developers: invalid custom properties, shorthands that reset values, layer order with !important, containing blocks, margin collapsing, specificity of :is() and :where(), intrinsic minimum sizes, and more, each checked in Chrome.
Quiz: CSS Interview Questions
Thirty front-end interview questions: cascade, specificity and layers, box model and margin collapsing, stacking contexts, positioning, flexbox and grid, responsive design, custom properties, performance, accessibility, modern selectors and architecture.
Quiz: CSS Course Final Exam
Thirty questions across the whole CSS course: syntax and error handling, selectors, the cascade and layers, values and units, color, the box model, backgrounds, positioning, flexbox, grid, responsive design, typography, generated content, effects, transforms, motion and architecture.
Quiz: CSS Architecture, Tooling and Debugging (CSS Part 17)
Twenty questions on modular CSS and BEM, layering a stylesheet, design tokens and theming, pattern libraries and safe refactoring, preprocessors and build tools, the at-rules reference, and debugging common CSS problems.
Discussion
Sign in to ask a question or share what you learned.