Introduction to CSS

How a CSS Rule Looks

A CSS rule set is composed of two parts:

  • Selector – identifies the HTML element(s) you want to style.
  • Declaration block – contains one or more declarations, each made up of a property and a value.

Example: Single Rule

Code Block Loading...

Here, p is the selector. It applies one rule that sets the font-size property to 20px.

Example: Multiple Rules

Code Block Loading...

Selectors can be stacked, each with its own declaration block.

Example: Targeting Multiple Elements

Code Block Loading...

This rule applies the same style to both <p> and <a> elements.

Selectors can target:

  • HTML tags (e.g., p, a)
  • Classes (e.g., .my-class)
  • IDs (e.g., #my-id)

Advanced selectors can match elements based on attribute values or respond to pseudo-classes (covered later).

Semicolons

Every CSS declaration ends with a semicolon (;).

  • Technically, the last rule in a block can omit it.
  • Best practice: always include semicolons for consistency and to avoid errors when adding new properties later.

Formatting and Indentation

CSS doesn’t enforce strict formatting rules, but clean code is easier to read and maintain.

Valid but Hard to Read:

Code Block Loading...

Recommended Formatting:

Code Block Loading...

Best practices:

  • Place the opening brace { on the same line as the selector, separated by one space.
  • Indent declarations (commonly 2 spaces).
  • Align closing braces } to the left.

Consistent spacing and indentation act as a visual guide, making your CSS more understandable and professional.