2. CSS Syntax

What you will learn

  • The parts of a CSS rule
  • How to write several declarations
  • How to style several selectors at once

Anatomy of a rule

A CSS rule (or rule set) has a selector and a declaration block.

Syntax

selector {
  property: value;
  property: value;
}
Part Meaning Example
Selector Which elements to style h1
Declaration block Everything between { } { color: navy; }
Property What to change color
Value What to change it to navy

An example with several declarations

Example

<style>
  h2 {
    color: navy;
    text-align: center;
    background-color: lightyellow;
  }
</style>

<h2>Centered heading</h2>

Output

Centered heading

The rules of the syntax

  • A colon separates a property from its value.
  • A semicolon ends each declaration. The last one can omit it, but always include it so adding more lines later is safe.
  • Property names are written in lowercase, with hyphens: background-color.
  • Spaces and line breaks do not matter. One declaration per line is easier to read.

Grouping selectors

Separate selectors with commas to give them the same style. This saves repeating yourself.

Example

<style>
  h1, h2, p {
    color: darkgreen;
    font-family: Arial, sans-serif;
  }
</style>

<h1>Main title</h1>
<h2>Subtitle</h2>
<p>A paragraph.</p>

Output

Main title

Subtitle

A paragraph.

What happens when something is wrong?

CSS does not show error messages on the page. If a declaration has a mistake, the browser skips it and carries on. When a style does not work, check for:

  • a missing colon, semicolon, or closing brace,
  • a misspelled property, such as colour instead of color,
  • a value that does not belong to that property.

Press F12 in your browser to open developer tools, which show which rules were applied or ignored.

Common mistakes

  • Using = instead of :.
  • Forgetting the closing }, which can break every rule after it.
  • Using British spelling for property names: write color, not colour.

Exercise

Make both h1 and p centered with one rule.

Show solution
<style>
  h1, p {
    text-align: center;
  }
</style>
<h1>Welcome</h1>
<p>Hello there.</p>

Knowledge check

1. Which symbol separates a property from its value?

A colon (:).

2. Which symbol ends a declaration?

A semicolon (;).

3. How do you apply one rule to h1 and h2?

Separate the selectors with a comma: h1, h2 { ... }

Summary

  • A rule is a selector plus a block of property: value declarations.
  • Colons separate properties from values, and semicolons end declarations.
  • Group selectors with commas.

Scroll to Top