CSS Basics: The Syntax That Matters & The Syntax That Doesn’t

When you’re starting to play around with CSS at the very beginning, like any other language, you have to get used to the syntax. Like any syntax, there are a bunch of little things you need to know. Some characters and the placement of them is very important and required for the CSS to work correctly. And some characters are more about clean looking code and generally followed standards but don’t matter for the CSS to work.

First, so we have the terminology down:

A CSS ruleset consists of a selector and delcaration(s) wrapped in curly braces.

Important: Braces

If you miss the opening brace, CSS will keep reading as if the next bit of text is still part of the selector. Then it’s likely to find a character like : which are invalid as part of a selector and break. Breaking likely means it will screw up itself and the next ruleset, and recover after that.

Missing a closing brace is a bit worse in that it’s likely to mess up the rest of the entire CSS file unless it somehow finds a double closing brace and can resolve that first missing one.

Overall point: braces are very important!

Preprocessing languages like Sass and Less offer a syntax feature called nesting. This can be convenient, but note that when these preprocessors run and produce CSS, that nesting is removed because CSS by itself doesn’t support that. If you copy nested CSS into regular CSS, you’ll have problems with the braces.

Sometimes Important: Spaces

There are just a few places that spaces are important in CSS. One of the most imortant is in selectors. One space in a selector means you’re selecting descendants of the previous part of the selector. The selector body p means “select p elements that are descendants of the body element”. That space means a lot. Hopefully it’s clearly different than bodyp which won’t select anything (there is no <bodyp> element). But it’s not different from body p. Multiple spaces mean the same as one space.

I’d encourage you to be consistent with your spacing, and produce clean and readable CSS. You might want to reference some CSS style guides out there for some formatting best practices.

Even the !important rule in CSS, which comes after a the value in a delcaration like body { background: white !important; } doesn’t have any spacing requirements. It could have any amount of space before it, or none.

The removing of space in CSS is actually a best practice for performance, so you might notice that when peeking at the raw CSS of websites in production.

You’re better off leaving that minification of CSS to a tool that processes your CSS for you, leaving the original alone. We’ll have to cover the options for that in other post.

Mostly Important: Semicolons

Each declaration in a ruleset (a property and value pair) ends in a semicolon. That semicolon is required, otherwise CSS will keep reading the next property as if it’s part of the value of the previous declaration.