2. The Anatomy of a CSS Ruleset
A CSS ruleset is the basic building block of any stylesheet. It tells the browser which element to style and how to style it.
Structure of a Ruleset
A ruleset consists of three main parts:
- Selector: The element(s) you want to target (e.g.,
p,.main-heading,#logo). - Declaration Block: The instructions on how to style the targeted element (enclosed in curly braces
{}). - Declaration: A single pair of a Property and its Value, separated by a colon (
:), and terminated by a semicolon (;).
css /* 1. Selector / body { / 2. Declaration Block */
/* 3. Declaration (Property: Value;) */ background-color: #f4f4f4; font-family: Arial, sans-serif; margin: 0; }
Key Syntax Rules
- Curly Braces: Declarations must be wrapped in
{}. - Colons: Properties and values are separated by a colon.
- Semicolons: Every declaration must end with a semicolon (even the last one, although optional, it is highly recommended for clarity and avoiding errors).
- Case Sensitivity: CSS properties and keywords are generally case-insensitive, but values (especially font names or file paths) might be case-sensitive depending on the environment.
Writing Clean CSS
While CSS ignores most whitespace, using consistent indentation and placing each declaration on its own line drastically improves readability.
Bad Practice: css h1{color:red;font-size:30px;}
Good Practice: css h1 { color: red; font-size: 30px; }