Priya’s page now has a place for everything the script will fill, each with its own id, but it still looks like a plain document. Soon the script will mark the games that run over an hour as long, and Priya wants those games to stand out. That’s CSS’s job.
In this lesson, you’ll link a stylesheet to Priya’s page and read its rules the way the browser does. You’ll write selectors that pick out exactly the elements you mean and work out which rule wins when two of them disagree. You can use that knowledge to make sure a state class, which marks a condition such as a game being long, changes how the page looks.
Link a Stylesheet to the Page
Priya’s page needs somewhere to keep its look, separate from its content, in the same way main.js keeps the script out of index.html. That place is a stylesheet, a file of CSS rules. In VS Code, create a new file named style.css in your scratch folder, next to index.html, and give it one rule:
scratch/style.css
h1 {
color: crimson;
}
This is a CSS rule, and it has two parts. The h1 before the opening brace is the selector, which says which elements the rule applies to. Inside the braces is a declaration: a property, color, then a colon, then a value, crimson, and a semicolon to end it. A rule can hold many declarations, one per line. CSS knows over a hundred color names like crimson.
The browser won’t read style.css until the page asks for it. Open scratch/index.html and add a link element at the end of its head:
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Game Night</title>
<link rel="stylesheet" href="style.css">
</head>
The link element connects the page to another file. Its rel="stylesheet" says what kind of file it is, and href gives its path. Like the meta elements, link is a void element, so it has no end tag.
The path style.css is relative: the browser reads it starting from the page’s own address. It takes http://127.0.0.1:3000/scratch/index.html, drops index.html, and adds style.css, so it asks the server for http://127.0.0.1:3000/scratch/style.css. That’s the same rule that finds main.js from the script tag. If the stylesheet sat in a css folder next to the page, the href would be css/style.css.
Save both files. The page reloads, and the heading Priya’s Game Night is now crimson. If it’s still black, check the href against the file’s name and folder. The Console then shows a red line starting with Failed to load resource that mentions a 404 status. That means the server looked for the file at that path and didn’t find it.
Pick Elements With Selectors
The h1 rule colors every h1, which is fine with only one. The games need more precise aim: a rule for the games list alone, and later one for only the long games. To have games to look at, add two by hand to the empty games list in scratch/index.html: