CSS Syntax and Comments
The rules of CSS grammar — declarations, whitespace, shorthand, and how to comment your stylesheets.
2 phút đọc
Before diving into selectors and properties, it's worth getting comfortable with the small grammatical details of CSS — the things that cause silent bugs when you get them wrong.
Declarations end in semicolons
.card {
padding: 16px;
border-radius: 8px;
background-color: white
}Every declaration should end with a semicolon. The last one in a block is technically optional (as shown with background-color above), but leaving it off is a common source of bugs the moment you add another declaration after it and forget to add the missing semicolon first. Always include it.
Whitespace is (mostly) ignored
.card{padding:16px;border-radius:8px}
.card {
padding: 16px;
border-radius: 8px;
}Both of these are identical to the browser. CSS doesn't care about indentation, line breaks, or extra spaces between tokens — it only cares about the tokens themselves and the punctuation (colons, semicolons, braces) that separates them. The multi-line version exists purely for humans; use it consistently so stylesheets stay readable as they grow.
Comments
/* This is a comment */
.card {
/* TODO: revisit this spacing once the design review lands */
padding: 16px;
}CSS comments use /* ... */ — there's no single-line // comment like in JavaScript. Comments are stripped out before the browser applies any styles, so they're free to use liberally for explaining why a rule exists, not just what it does (the "what" is usually obvious from reading the properties).
Shorthand properties
/* Longhand */
.box {
margin-top: 8px;
margin-right: 16px;
margin-bottom: 8px;
margin-left: 16px;
}
/* Shorthand, same result */
.box {
margin: 8px 16px;
}Many CSS properties have a shorthand form that sets several related longhand properties at once. margin: 8px 16px sets vertical margin to 8px and horizontal margin to 16px in one line. Shorthand is convenient, but be aware it resets every longhand property it covers — even ones you didn't mention — to a default if you don't specify them, which can silently override a value you set elsewhere.
Case sensitivity
Property names and most keyword values are case-insensitive in practice, but the convention is lowercase for everything except things that are inherently case-sensitive, like font names or URLs referencing a file system. Class and ID selectors, however, are case-sensitive, so .Card and .card are two different selectors — a frequent source of "why isn't my style applying" confusion.