Every CSS rule is built from a selector, which targets specific HTML elements, and a declaration block, delimited by curly braces, containing one or more declarations, each a property name followed by a colon, a value, and a terminating semicolon. Whitespace, indentation, and line breaks inside a rule are entirely optional and purely for human readability, since the CSS parser only cares about the actual tokens, selectors, braces, colons, and semicolons, not how they're formatted, though a missing semicolon between declarations, or a missing closing brace, will break the rule.
1Understanding CSS Syntax
Every CSS rule is built from a selector, which targets specific HTML elements, and a declaration block, delimited by curly braces, containing one or more declarations, each a property name followed by a colon, a value, and a terminating semicolon. Whitespace, indentation, and line breaks inside a rule are entirely optional and purely for human readability, since the CSS parser only cares about the actual tokens, selectors, braces, colons, and semicolons, not how they're formatted, though a missing semicolon between declarations, or a missing closing brace, will break the rule.
Always terminate a declaration with a semicolon, even the last one in a block — while CSS technically allows omitting the semicolon before a closing brace, doing so is a common source of bugs the moment you later add another declaration after it and forget to add the semicolon you skipped.
p {
color: blue;
font-size: 16px;
}2Practical Example
Here is a real-world application of CSS Syntax showing how it is used in production CSS code.
.card {
padding: 20px;
border: 1px solid gray
}
.title {
font-weight: bold;
}3Best Practices
Follow these guidelines when working with CSS Syntax:
1. Always terminate every declaration with a semicolon, including the last one in a block, to avoid an easy-to-miss bug when adding a new declaration later
2. Use consistent indentation and one declaration per line for readability, even though CSS itself doesn't require any particular formatting
3. Double-check for a missing closing brace when an entire rule, or subsequent rules, appear to not apply at all, since one unclosed rule can silently swallow the rules that follow it
Tip: Always terminate a declaration with a semicolon, even the last one in a block — while CSS technically allows omitting the semicolon before a closing brace, doing so is a common source of bugs the moment you later add another declaration after it and forget to add the semicolon you skipped.
p {
color: blue;
font-size: 16px;
}