Skip to content

CSS Syntax

Understanding the basic structure of CSS rules.

A fundamental CSS unit is the rule set. Each rule set consists of two main parts:

  1. Selector: Targets the HTML element(s) you want to style.
  2. Declaration Block: Contains one or more style declarations, enclosed in curly braces {}.

Visualizing the parts:

Selector { Declaration Block }

Each declaration includes:

  • A Property: The style attribute you want to change (e.g., color, font-size, margin).
  • A Value: The specific setting for that property (e.g., red, 16px, 10px).

The property and value are separated by a colon (:).

Each declaration within a block must end with a semicolon (;). This semicolon separates multiple declarations.

Visualizing a declaration:

property: value;

Let’s look at a complete CSS rule set:

p {
color: red;
text-align: center;
}

Breaking it down:

  • p is the selector. It targets all <p> (paragraph) elements.
  • { ... } encloses the declaration block.
  • color: red; is the first declaration.
    • color is the property.
    • red is the value.
    • ; is the semicolon separating it from the next declaration.
  • text-align: center; is the second declaration.
    • text-align is the property.
    • center is the value.
    • ; is the semicolon ending the declaration (and the block, in this case).

This rule set tells the browser to make all paragraph text red and center-aligned.

Readability: While you can write CSS on a single line (p {color:red; text-align:center;}), putting each declaration on its own line, indented within the curly braces, is standard practice and makes the code much easier to read and maintain.

Comments are used to explain your code for yourself or other developers. They are completely ignored by the browser.

CSS comments start with /* and end with */. They can span multiple lines.

/* This is a single-line comment */
p {
color: blue; /* Set the text color */
font-size: 16px;
}
/*
This is a
multi-line comment.
It explains the purpose of the following rule.
*/
.highlight {
background-color: yellow;
}

Use comments to document complex sections, explain non-obvious choices, or temporarily disable code (‘commenting out’).