Sub topic 4
Connect a stylesheet and write your first rules
This chapter assumes you can already write the HTML skeleton and semantic landmarks from the earlier chapters. You should be able to save files in one folder and open them in a browser. By the end you will link a CSS file to your page, read and write a CSS rule, pick elements with the common selectors, and diagnose the usual reasons a style does not show up.
What a stylesheet does
HTML describes what the content is. CSS (Cascading Style Sheets) describes how it looks. A stylesheet is a plain text file, usually ending in .css, that holds a list of rules. The browser reads the HTML, builds the page, then applies the rules to the matching elements.
Keeping styles in a separate file has practical benefits:
- One file styles every section, so a color change happens in one place.
- The browser can cache the file, so it is not downloaded again on each visit.
- The HTML stays readable, because it holds structure and content only.
Link the stylesheet
Create a file named styles.css in the same folder as index.html. Then add a link element inside the head:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Jane Doe | Web Developer</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<main>
<h1>Jane Doe</h1>
<p>I build small, fast websites.</p>
</main>
</body>
</html>The link element has two attributes that matter here:
rel="stylesheet"tells the browser what kind of resource this is.href="styles.css"is the path to the file, relative to the HTML file.
link is a void element, so it has no closing tag. Put it in the head, so the browser knows about the styles before it paints the body. That avoids a flash of unstyled content.
Other ways to attach CSS
You can also write rules inside a style element in the head, or in a style attribute on a single tag. Both work, but neither suits this site. The style element cannot be shared between pages or cached separately. The style attribute is hard to override and mixes presentation into your content. Use a linked file.
Anatomy of a rule
A rule has a selector and a declaration block:
p {
color: #1f2933;
line-height: 1.6;
}pis the selector. It says which elements the rule applies to.- The braces
{ }wrap the declaration block. color: #1f2933;is a declaration. It is a property (color), a colon, a value (#1f2933), and a semicolon.
Whitespace is free, so you can lay out a rule on one line or many. Most people put one declaration per line, which keeps diffs and error hunting simple.
Comments use /* ... */ and can span lines. // is not a CSS comment.
/* Page-wide defaults */
body {
margin: 0; /* remove the browser's default 8px gap */
font-family: system-ui, sans-serif;
}Selectors you will use on this site
A selector decides which elements a rule touches. These five cover most of a one-page site.
| Selector type | Example | Matches |
|---|---|---|
| Type | `h2` | Every `h2` element |
| Class | `.project-card` | Elements with `class="project-card"` |
| ID | `#about` | The one element with `id="about"` |
| Descendant | `nav a` | Any `a` that sits somewhere inside a `nav` |
| Pseudo-class | `a:hover` | An `a` while the pointer is over it |
You can also group selectors with commas, so they share one block:
h1,
h2,
h3 {
line-height: 1.2;
}Each selector in the list is evaluated on its own. This is not the same as a descendant selector, which uses a space and no comma.
Classes and IDs
A class is reusable. Add it in the HTML, then target it with a leading dot:
<article class="project-card">
<h3>Recipe Finder</h3>
<p>A small search tool for weeknight dinners.</p>
</article>.project-card {
border: 1px solid #cbd2d9;
padding: 1rem;
}An element can carry several classes, separated by spaces: class="project-card featured". An ID must be unique in the page. On this site, IDs already exist as anchor targets (#about, #projects), so you will usually style by class and keep IDs for linking.
A good habit is to name classes by what the thing is (project-card), not how it looks (blue-box). The look will change, and the name should survive that.
Combining a type with a class or a pseudo-class
Write the parts together with no space. Compare:
a.button {
background: #0b5cad;
color: #ffffff;
}
a:hover,
a:focus-visible {
text-decoration: underline;
}a.button means an a that also has the class button. a .button (with a space) would mean an element with class button inside an a. That one missing space is a frequent source of "my rule does nothing".
Values and units you will meet first
Most declarations take one of a few kinds of value:
- Keywords, such as
none,center, orbold. - Colors, such as
#0b5cad,rgb(11 92 173), orwhite. - Lengths, such as
16px,1rem,60rem, or50%. - Unitless numbers, such as
line-height: 1.6.
For lengths, prefer rem for sizes and spacing. One rem equals the root font size, which is 16px by default. Users who raise their browser's default text size then get proportionally larger spacing too. Zero needs no unit: margin: 0.
A first stylesheet
Put this in styles.css. It uses only what this chapter covered, and later chapters replace the hard-coded values with variables.
/* Reset the gap the browser adds around the page */
body {
margin: 0;
font-family: system-ui, sans-serif;
line-height: 1.6;
color: #1f2933;
background: #ffffff;
}
/* Center the content in a readable column */
main {
max-width: 60rem;
margin: 0 auto;
padding: 2rem 1rem;
}
h1 {
font-size: 2.5rem;
line-height: 1.2;
}
a {
color: #0b5cad;
}
a:hover {
color: #083d73;
}Reload index.html. The text should change font, the heading should grow, and the content should sit in a centered column. If nothing changes, work through the checklist below.
Why a rule does not apply
Check these in order. They account for most first-week CSS problems.
- Wrong path. Open the browser's developer tools (F12), go to the Network tab, and reload. A
styles.cssentry with status 404 means thehrefdoes not match the real file name or folder. Paths are case-sensitive on most web servers, soStyles.cssandstyles.cssdiffer. - Link in the wrong place or malformed. Confirm
rel="stylesheet"is spelled correctly and the tag sits in thehead. - Syntax error. A missing semicolon, a missing closing brace, or a colon replaced by a semicolon breaks that declaration. A missing
}can also swallow the next rule. The browser skips invalid parts silently and does not show an error on the page. - Misspelled property or value.
colour: redandmargin: 1 remare ignored. - Selector mismatch. A class written as
.project-cardin CSS butprojectcardin HTML matches nothing. - Another rule wins. Two rules can target the same element. The browser picks one using the cascade and specificity, which a later chapter covers.
- Stale cache. Do a hard reload (Ctrl+Shift+R, or Cmd+Shift+R on macOS).
Keeping the file readable
A stylesheet grows. Some conventions that help on a one-page site:
- Order rules roughly as the page reads: global defaults first, then header and navigation, then each section.
- Group related rules under a comment heading.
- Keep selectors short. A long chain such as
main section div ul li ais fragile, because any change to the HTML structure breaks it. A class on the element is more stable. - Use consistent formatting: two-space indents, one declaration per line, a space after each colon.
Summary of the working model
The browser downloads the HTML, follows the link to the stylesheet, parses each rule, and finds every element that matches each selector. It then applies the valid declarations. Invalid declarations are dropped without a message, so the developer tools are your debugger. Next, you will see how the cascade resolves conflicts between rules.
Exercise
Your page has <link rel="stylesheet" href="css/styles.css">, but the file is saved next to index.html as styles.css, and none of your rules apply. What is wrong, how can you confirm it, and what are two ways to fix it?
Show answer
The href points to a css folder that does not exist, so the request returns 404. Confirm it in the developer tools Network tab, where css/styles.css shows a 404 status. Fix it either by changing the href to styles.css, or by creating a css folder and moving the file into it.
Exercise
What is the difference between the selectors nav a, nav, a and a.nav?
Show answer
nav a matches any a element inside a nav. nav, a is a group that matches every nav element and every a element separately. a.nav matches an a element that has the class nav.