CSS Syntax

This page explains how CSS is written and how the browser reads your rules.

It covers selectors, declarations, values, comments, formatting, and common mistakes. Use it as a reference before moving on to layout or advanced topics.

What is CSS Syntax?

CSS uses a simple pattern:

  • Select something in HTML
  • Apply one or more style rules to it

Correct syntax ensures the browser can understand your styles. Incorrect syntax usually causes the rule to be ignored.


Anatomy of a CSS Rule

Selector

The selector chooses which HTML elements the rule applies to.
Examples:

  • p (element selector)
  • .button (class selector)
  • #main (ID selector)
  • nav a (descendant selector)

Declaration Block

Curly braces { } contain one or more declarations.

Declarations

A declaration has a property and a value:

property: value;

Each declaration ends with a semicolon.

Example

p {
 text-align: center;
}

p is the selector; inside are two declarations.


Comments & Whitespace

  • Comments use: /* comment */
  • Whitespace (spaces, line breaks) does not affect how CSS works
  • Indentation and line breaks make code easier to read

Grouping Selectors & Multiple Rules

You can apply the same styles to multiple selectors:

h1, h2, h3 {
 font-family: sans-serif;
}

You can also write multiple rules in one stylesheet — each selector gets its own block.


Units & Values

CSS values may use:

  • Keywords (e.g., auto, inherit)
  • Length units (px, em, rem, %)
  • Colours (red, #ff0000, rgb(255,0,0))

A property only accepts certain value types — invalid values are ignored.


Using CSS in a Page

External Stylesheet (recommended)

<link rel=”stylesheet” href=”styles.css”>

Internal Styles

<style>

  p { color: blue; }

</style>

Inline Styles

<p style=”color: blue;”>Hello</p>

External stylesheets are cleaner and easier to maintain.


Common Mistakes

  • Missing semicolons
  • Misspelled properties or selectors
  • Wrong value types (e.g., margin: red;)
  • Overly specific selectors causing conflicts
  • Missing braces { }