CSS Error Handling

By

Learn how CSS handles errors: unlike JavaScript, it stays resilient and skips an invalid line, so a missing semicolon can quietly break the rules around it.

~~~

CSS handles errors by skipping what it can’t understand and moving on. It does not act like JavaScript, which packs up all its things and goes away altogether, terminating all the script execution after the error is found.

CSS tries very hard to do what you want.

If a declaration has an error, the browser drops that declaration and keeps applying the rest.

Why is CSS so forgiving?

This behavior is intentional. It’s what allows CSS to evolve.

When a browser meets a property it doesn’t know, maybe because it’s brand new or misspelled, it ignores it and continues:

p {
  colr: black;
  font-size: 20px;
}

Here colr is dropped, but font-size still applies. Thanks to this, you can use new CSS features today. Older browsers won’t break the page, they’ll just skip what they don’t recognize.

The missing semicolon problem

Sometimes an error takes down more than the line it’s on.

If you forget the semicolon on one line:

p {
  font-size: 20px
  color: black;
  border: 1px solid black;
}

the line with the error AND the next one will not be applied, but the third rule will be successfully applied on the page. The parser scans forward until it finds a semicolon. At that point the declaration is font-size: 20px color: black;, which is invalid, so it skips it.

You lose two declarations from a single typo.

An error that removes the whole rule

Declarations fail one by one, but selectors are stricter. If one selector in a comma separated list is invalid, the browser drops the entire rule:

p, p:hoover {
  color: red;
}

The typo in :hoover (it should be :hover) invalidates the whole selector list. Even the plain p paragraphs lose the red color.

Be careful with this when you group many selectors in one rule. Splitting them into separate rules limits the damage a single typo can do.

How do you find these errors?

The browser won’t print anything to the console. That’s the tricky part: the page just looks slightly wrong, and you have to figure out why.

Open the browser DevTools and inspect the element. In the styles panel, invalid declarations show up crossed out, with a warning icon next to them. That’s the fastest way to spot a broken line.

This is also why tools like CSS Lint exist. They catch typos and syntax errors before the browser silently swallows them.

Tagged: CSS · All topics
~~~

Related posts about css: