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:
- External file (best):
<link rel="stylesheet" href="style.css">in the<head>. - Internal: a
<style>element in the head. - 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
- Goal: make every <h2> dark green and centred.
- Selector: h2. Declarations: color: darkgreen; text-align: center;
- Result: one rule that styles all h2 elements on every page that loads the file.
h2 {
color: darkgreen;
text-align: center;
}