TutreNews Learn

Rules, selectors and the cascade

What CSS does and how a rule is built

Goal: Read and write a CSS rule and attach CSS to HTML · 8 min

HTML describes the structure and meaning of a page; CSS (Cascading Style Sheets) describes its appearance: colours, spacing, fonts and layout. Keeping them apart means that one stylesheet can restyle a hundred pages.

A CSS rule has a selector and a declaration block:

h1 {
  color: navy;
  font-size: 2rem;
}
  • h1 is the selector: which elements are styled.
  • Inside the braces are declarations, each of the form property: value;.
  • Every declaration ends with a semicolon; a missing one breaks the next declaration.
  • Comments look like /* note */.

Three ways to attach CSS:

  1. External file (best): <link rel="stylesheet" href="style.css"> in the <head>.
  2. Internal: a <style> element in the head.
  3. Inline: <p style="color: red"> (only for quick tests; it is hard to maintain and overrides most rules).

Browsers ignore declarations they do not understand and carry on, so a typo such as colour: red silently does nothing. Check spelling first when a style does not work.

Worked example: Styling a heading

  1. Goal: make every <h2> dark green and centred.
  2. Selector: h2. Declarations: color: darkgreen; text-align: center;
  3. Result: one rule that styles all h2 elements on every page that loads the file.
h2 {
  color: darkgreen;
  text-align: center;
}