Leet School

{module 4}

How CSS works: selectors, properties and values

Making it look right with CSS20 min read

What you will be able to do

  • Link a stylesheet to a page and write rules in it.
  • Choose between a type selector and a class selector to style the right elements.
  • Work out which rule wins when two rules disagree, and check your answer in the developer tools.

Why it matters

Saffron Sweets is a sweet shop in Jaipur, India. Kavita Sharma, the owner, has a page in plain HTML that lists the sweets of the day, black on white. Some days she adds a special sweet, made for that day only. Customers did not notice it in the list, and at closing time trays of it were left over.

Kavita wanted the special sweet to stand out, and the shop name in the deep red of her shop sign. HTML says what each part of a page is, not how it looks. That is the job of a second language, CSS. With a few lines of CSS, one sweet looks different from the rest, and the HTML barely changes.

The idea

CSS is the language that says how a page looks: colours, sizes, spacing and layout. CSS is written in a file of its own, called a stylesheet. Its name ends in .css, and in this course it is always called styles.css. It sits in the same folder as the page.

The page asks for the stylesheet with one line in its head:

From index.html
<link rel="stylesheet" href="styles.css" />

The link element connects the page to another file. rel="stylesheet" says what kind of file it is, and href gives its name, as in a link. Like meta, link has no closing tag.

A rule

A stylesheet is a list of rules. Here is one:

From styles.css
h1 {
  color: maroon;
}

A rule has two parts.

  • The selector, here h1, says which elements the rule is for.
  • Between the curly braces, { and }, are the declarations. Each declaration is a property, a colon, a value and a semicolon.

The property color is the colour of the text, and maroon is a dark red. CSS knows the names of more than 140 colours, and lesson 2 shows a more exact way to write any colour. CSS spells its words the American way: color, not colour.

Text between /* and */ is a comment: a note for the next person, which the browser ignores.

Type selectors and class selectors

The selector h1 is a type selector: the name of an element. It matches every element of that type, so li matches every item of every list.

To style only some elements, mark them with a class attribute and a name you choose:

From index.html
<li class="special">Ghevar, today only, $5</li>

A class selector is that name with a full stop in front of it. It matches every element that has the class, whatever its type.

From styles.css
.special {
  color: maroon;
  font-weight: bold;
}

The property font-weight sets how thick the letters are, and bold makes them thick. Choose a class name that says what the thing is, such as special, not how it looks, such as red-text. If the colour changes later, special is still true.

Which rule wins

The item with the class special is matched by two rules, and both set color:

From styles.css
.special {
  color: maroon;
  font-weight: bold;
}

li {
  color: dimgrey;
}

The browser decides in two steps, called the cascade. CSS stands for Cascading Style Sheets.

  1. The more specific selector wins. CSS counts a class selector as more specific than a type selector, so .special wins over li, even though the li rule comes later in the file.
  2. When two selectors are equally specific, the rule that comes later in the file wins.

Some properties also pass from an element to the elements inside it. This is called inheritance. A text colour set on body reaches every heading, paragraph and list item that has no colour of its own.

Worked example

Open Visual Studio Code and make a folder called saffron-sweets. In it, make a file called index.html:

index.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Saffron Sweets, Jaipur</title>
    <link rel="stylesheet" href="styles.css" />
  </head>
  <body>
    <h1>Saffron Sweets</h1>
    <p>Sweets made by hand every morning in Jaipur.</p>
    <h2>Today's sweets</h2>
    <ul>
      <li>Kaju katli, box of 250 g, $6</li>
      <li>Motichoor ladoo, box of 6, $4</li>
      <li class="special">Ghevar, today only, $5</li>
      <li>Rasgulla, tin of 8, $7</li>
    </ul>
    <p class="note">Prices are in US dollars.</p>
  </body>
</html>

In the same folder, make a second file called styles.css:

styles.css
/* Styles for the Saffron Sweets page. */
body {
  color: black;
}

h1 {
  color: maroon;
}

h2 {
  color: maroon;
}

.special {
  color: maroon;
  font-weight: bold;
}

li {
  color: dimgrey;
}

.note {
  font-style: italic;
}

Save both files and open index.html in your browser. The words are the same as they would be without CSS:

Output
Saffron Sweets

Sweets made by hand every morning in Jaipur.

Today's sweets
Kaju katli, box of 250 g, $6
Motichoor ladoo, box of 6, $4
Ghevar, today only, $5
Rasgulla, tin of 8, $7

Prices are in US dollars.

What changed is how they look. The two headings are dark red. The sweets are grey, except the ghevar, which is dark red and bold. The last line is in italic letters, which lean to the right: that is font-style: italic.

Ask the browser what it decided

You do not have to guess which rule won. Right-click the ghevar line and choose Inspect. The developer tools open on the Elements panel, with the li selected. Chrome and Edge share the same tools, so these steps work in both.

Beside the elements is the Styles tab. It lists every rule that matches the selected element. The color of the li rule is crossed out there, because it lost. Next to Styles, the Computed tab shows the final value of each property. In Firefox, these two views are called Rules and Computed.

Here is the computed colour of four elements:

Output
h1: rgb(128, 0, 0)
first li: rgb(105, 105, 105)
li.special: rgb(128, 0, 0)
p.note: rgb(0, 0, 0)

The browser reports a colour as three numbers from 0 to 255, for red, green and blue. rgb(128, 0, 0) is maroon and rgb(105, 105, 105) is dim grey. No rule sets a colour for the note, so it inherits black from body.

The browser reports the weight as a number. 400 is normal and 700 is bold:

Output
first li: 400
li.special: 700

Maroon on white has a contrast ratio of about 11 to 1, and dim grey on white about 5.5 to 1. Lesson 2 explains what those numbers mean and how to measure them.

When two rules are equally specific

Add a second .special rule at the top of the file, with color: teal;. The two selectors are the same, so they are equally specific. The later rule wins, and the ghevar stays maroon:

Output
rgb(128, 0, 0)

Common mistakes

A mistake in CSS usually shows no message. The browser skips what it cannot read and carries on. To find the mistake, ask the browser what it really used, in the Styles and Computed tabs.

From wrong-link.html
<link rel="stylesheet" href="style.css" />

The file is called styles.css, with an s, and the link asks for style.css. The browser cannot find the file, so no rule applies. The heading is black, the colour every browser starts with:

Output
rgb(0, 0, 0)

This mistake is the one case that leaves a message. Open the Console, which you met in module 1, and you see this:

Output
Failed to load resource: net::ERR_FILE_NOT_FOUND

The browser asked for a file and did not find it. When nothing at all is styled, check the link first. The name in href must match the file name exactly. Match capital and small letters too: Windows and macOS usually forgive the difference, and GitHub Pages does not.

British spelling in a property

From colour.css
h1 {
  colour: maroon;
}
Output
rgb(0, 0, 0)

No property is called colour, so the browser ignores the declaration and the heading inherits black. The Styles tab shows the line crossed out, with a warning sign. In CSS, write color.

A class selector without its full stop

From no-dot.css
special {
  color: maroon;
  font-weight: bold;
}
Output
color: rgb(105, 105, 105)
font-weight: 400

The ghevar is grey and not bold, like every other sweet. Without the full stop, special is a type selector. It looks for elements called special, and HTML has none.

Think it through

Kavita now wants both headings in dark green, the colour of a new sign. Ama, a learner who helps her, does the change.

Understand. The h1 and the h2 change from maroon to dark green. Nothing else changes.

Break down. Find every place the heading colour is set. Change it. Make the next change quicker.

Plan. The colour is written twice, in the h1 rule and the h2 rule. Ama could change both. But a comma joins selectors that share their declarations: h1, h2 matches every h1 and every h2. She plans one rule with the colour name darkgreen, so the heading colour is in one place.

Build. She replaces the two rules with one, with h1, and h2 on separate lines and color: darkgreen; inside, and a comment above it. She saves and reloads.

Test. In the Computed tab, both headings show rgb(0, 100, 0), which is dark green. The odd case: an h3 added next week would not be green, because h3 is not in the selector. She notes that for Kavita.

Reflect. The fastest change was not the best one. Changing two lines would have worked today, and left two places to forget next time.

At work

Before you say how long a job will take, write down what it contains. "Make my page look nicer" sounds like one task. It is several, and you cannot estimate a task you have not named. Here is what Ama wrote to Kavita before she gave any time:

Kavita, here is what I understand the job to be.

  1. Add a stylesheet to the page.
  2. Headings in the colour of your sign. Please send me a photo of it.
  3. The special sweet of the day in bold and in that colour.
  4. The note about prices in italic letters.

Not included: new photos, new text or a new layout. Once you confirm the list, I will tell you how long it will take.

Every line can be checked. If Kavita replies "yes, and a photo of the shop", Ama knows the job has changed before she starts.

Your tasks

Task 1: Build and inspect

Make both files of the worked example and open the page. Inspect the ghevar line. Find the crossed-out color in the Styles tab, then color in the Computed tab.

You are done when the Computed tab shows rgb(128, 0, 0) for the ghevar line, and you have seen the crossed-out declaration of the li rule.

Task 2: Predict, then break

Make these three changes one at a time, and undo each one before the next. Before you reload, write down what you expect to see.

  1. Change the link to href="style.css".
  2. Change color to colour in the h1 rule.
  3. Move the li rule above the .special rule.

You are done when you have three predictions and three results, and you can explain any difference between them.

Task 3: Style your own page

Take the page you built for Kigali Threads in the module 2 project and link a new styles.css to it. Write one rule with a type selector and one with a class selector. Then write a rule that loses to another one.

You are done when your page uses both kinds of selector, and you can point to one crossed-out declaration and say why it lost.

Recap

  • A stylesheet is a .css file. The page asks for it with a link line in its head.
  • A rule is a selector and its declarations. Each declaration is written property: value;.
  • A type selector matches every element of that name. A class selector, with a full stop, matches every element with that class.
  • A class selector wins over a type selector. Between equals, the later rule wins.
  • CSS fails without a message. The Styles and Computed tabs show what the browser really used.

Go deeper