Rules and declarations
Definition and purpose
A style rule combines a selector and a declaration block. A declaration assigns a value to a property. A block can contain several declarations separated by semicolons. This structure lets one selection of elements receive multiple styles.
One rule, two declarations
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>CSS practice</title> <style>p { color: navy; background-color: white; }</style> </head> <body> <p id="a">Delivery confirmed</p> </body></html>The foreground and background are set independently.
Syntax and mental model
Read p { color: navy; background-color: white; } as: select paragraphs, then assign a foreground and background. Braces delimit the block, a colon separates a property from its value, and semicolons separate declarations. The final semicolon is optional before the closing brace, but consistently writing it prevents mistakes when adding a line.
Two different rules
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>CSS practice</title> <style>h2 { color: green; } p { color: navy; font-size: 18px; }</style> </head> <body> <h2 id="a">Hours</h2> <p id="b">Nine to five</p> </body></html>The second rule adds a font size to the paragraph; px is a CSS length unit introduced fully later.
Common mistakes
Do not use an equals sign in place of the colon or put the selector inside the declaration block. A valid property still needs an accepted value.
Practice and next steps
After trying the examples, complete the linked coding exercise and review questions. Predict the result before running your code. Prerequisite: Connect a stylesheet. Next lesson: Comments and syntax recovery.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Rules and declarations — knowledge check
Five questions on rules and declarations.
What is color in p { color: navy; }?
How many declarations are in p { color: navy; font-size: 18px; }?
Which punctuation separates a property from its value?
Which marks the boundaries of a declaration block?
Which rule sets both properties correctly?