CSS — Syntax
The grammar of CSS
Every CSS rule follows the same pattern:
h1 {
color: teal;
font-size: 40px;
}
Breaking it down:
h1 ← selector: "find every h1"
{
color: ← property
teal; ← value (note the colon between, semicolon after)
}
A selector picks elements. Inside { }, each declaration is property: value;.
Selectors you'll use daily
/* Tag — styles ALL <p> elements */
p { color: gray; }
/* Class — styles elements with class="note" (most common) */
.note { background: yellow; }
/* Id — styles THE element with id="header" */
#header { border-bottom: 2px solid black; }
/* Everything */
* { box-sizing: border-box; }
Classes beat ids for styling because they're reusable. Save ids for JavaScript hooks and unique page landmarks.
Combining selectors
/* Every .button INSIDE a nav */
nav .button { margin: 4px; }
/* Elements that have BOTH classes */
.card.featured { border-color: gold; }
/* Several selectors, one rule */
h1, h2, h3 {
font-family: Georgia, serif;
}
Comments and formatting
/* This is a CSS comment.
Use them to explain WHY a rule exists. */
.bad-example{color:red;margin:0} /* valid but painful to read */
Consistent spacing costs nothing and saves you at 3am.
Most common beginner error: forgetting a semicolon or closing brace. Symptom: the rule after your typo silently stops working too.
Related Topics
Frequently Asked Questions about Syntax
What is Syntax in CSS?
Syntax is a fundamental concept in CSS. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Syntax?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Syntax.
Why is Syntax important in CSS?
Syntax is essential for CSS development. Understanding this concept will help you write better code and solve real-world problems more effectively.