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:

CSS
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:

CSS
selector {
  property: value;
}

Consider this example:

CSS
h1 {
  color: green;
  font-size: 36px;
}

The different parts are:

  • h1 is the selector.
  • { } is the declaration block.
  • color and font-size are properties.
  • green and 36px are 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.

CSS
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.

CSS
background-color: yellow;

In this declaration:

  • background-color is the property.
  • yellow is the value.

Other examples include:

CSS
font-size: 20px;
width: 300px;
text-align: center;

Always place a colon (:) between the property and its value.

CSS
/* Incorrect */
color = red;

/* Correct */
color: red;

Using Semicolons

A semicolon (;) marks the end of a declaration.

CSS
.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:

CSS
h1{color:blue;font-size:32px;}

However, this format is difficult for people to read. A clearer version is:

CSS
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:

CSS
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.