CSS Syntax
Every piece of CSS is made of rules, and every rule follows the same simple pattern.
The Parts of a CSS Rule
Example
h1 {
color: blue;
font-size: 32px;
}| Part | In the example | Meaning |
|---|---|---|
| Selector | h1 | Which HTML elements the rule styles |
| Declaration block | { ... } | The curly brackets that hold the styles |
| Declaration | color: blue; | One style: a property and its value |
| Property | color | What you want to change |
| Value | blue | What you want to change it to |
Read the rule above like a sentence: "For every h1, make the colour blue and the font size 32 pixels."
Writing Declarations Correctly
- Put a colon
:between the property and the value - End each declaration with a semicolon
; - Put all declarations inside curly brackets
{ } - You can write many declarations in one rule
Example
<!DOCTYPE html>
<html>
<head>
<style>
p {
color: darkgreen;
font-size: 18px;
text-align: center;
background-color: #e8f5e9;
}
</style>
</head>
<body>
<p>Admissions are open for the new batch.</p>
<p>Classes start on Monday.</p>
</body>
</html>Try it Yourself »Both paragraphs get the same style, because the selector p matches every paragraph on the page.
The semicolon after the last declaration is optional, but always add it. If you later add another line and forget the semicolon, your CSS will break.
Spaces and New Lines
The browser does not care about extra spaces or new lines. These two rules do exactly the same thing:
Example
h2 { color: purple; margin: 0; }
h2 {
color: purple;
margin: 0;
}The second style, with one declaration per line, is much easier to read. Most developers use it.
CSS Comments
A comment is a note for humans. The browser ignores it. In CSS, a comment starts with /* and ends with */. It can be on one line or many lines.
Example
<!DOCTYPE html>
<html>
<head>
<style>
/* Main heading of the page */
h1 {
color: #264de4;
}
/*
Prices are shown in red
so customers notice them
*/
.price {
color: red;
font-weight: bold;
}
</style>
</head>
<body>
<h1>School Bag</h1>
<p class="price">Rs 1,850</p>
</body>
</html>Try it Yourself »Comments are also handy for turning off a line while you test something: wrap it in /* */ and it stops working until you remove the comment marks.
Common Mistakes
| Mistake | Wrong | Right |
|---|---|---|
| Missing colon | color red; | color: red; |
| Missing semicolon | color: red font-size: 20px; | color: red; font-size: 20px; |
| Wrong brackets | p ( color: red; ) | p { color: red; } |
| Space in a value with a unit | font-size: 20 px; | font-size: 20px; |
If a declaration has a mistake, the browser skips just that one declaration and keeps the rest.
Exercise
Exercise
In the rule p { color: red; }, what is "color"?
