CSS Syntax
Understand how CSS rules, selectors, properties, and values are written.
CSS syntax is the correct way of writing CSS instructions. It helps the browser understand:
- Which HTML element you want to style
- Which part of its appearance you want to change
- What value you want to apply
A basic CSS rule looks like this:
p {
color: blue;
}This rule changes the text colour of every <p> element to blue.
Structure of a CSS Rule
A CSS rule contains two main parts:
selector {
property: value;
}Consider this example:
h1 {
color: green;
font-size: 36px;
}The different parts are:
h1is the selector.{ }is the declaration block.colorandfont-sizeare properties.greenand36pxare values.- Each property-and-value pair is a declaration.
Declaration Block
The declaration block begins with { and ends with }. All styling instructions for the selected elements are placed inside these braces.
p {
color: brown;
font-size: 18px;
}Important points include:
- Use an opening brace after the selector.
- Keep every declaration inside the braces.
- Add a closing brace after the final declaration.
A missing brace may cause the browser to read the following CSS incorrectly.
Properties and Values
A property tells the browser what you want to change. A value tells it how that property should appear.
background-color: yellow;In this declaration:
background-coloris the property.yellowis the value.
Other examples include:
font-size: 20px;
width: 300px;
text-align: center;Always place a colon (:) between the property and its value.
/* Incorrect */
color = red;
/* Correct */
color: red;Using Semicolons
A semicolon (;) marks the end of a declaration.
.card {
color: black;
background-color: white;
width: 300px;
}The final declaration may sometimes work without a semicolon, but adding one is a good habit. It prevents errors when new declarations are added later.
Spacing and Line Breaks
The browser can understand CSS written on one line:
h1{color:blue;font-size:32px;}However, this format is difficult for people to read. A clearer version is:
h1 {
color: blue;
font-size: 32px;
}For readable CSS:
- Put the opening brace after the selector.
- Write one declaration on each line.
- Add a space after each colon.
- Indent declarations consistently.
- Close the rule with a separate brace.
Common CSS Syntax Mistakes
If a style is not working, check for:
- A missing colon between a property and value
- A missing semicolon
- An unclosed curly brace
- An incorrectly spelled property
- The wrong selector symbol
- A selector that does not match the HTML
For example:
p {
color blue;
font-size: 18px;
}The first declaration is missing a colon, so the browser may ignore it. The validfont-size declaration can still work.