Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Key Concepts

CSS is based around the concept of a stylesheet: a description of how an HTML document should be presented by the browser.

Stylesheets consist of a set of style rules. Each rule has the format

selector {
    property-name: property-value(s);
    ...
}

The selector is an expression that matches one or more elements in a document. Inside the braces are one or more property settings that will be applied to all the matching elements.

Each property setting consists of the property’s name, then a colon, then the value (or values) to be given to that property. A property setting is terminated with a semicolon.

We discuss selectors in more detail in the next section. For now, let’s consider the simplest possible selector: one which selects all occurrences of the given element.

Let’s suppose that you wish to target all level 1 headings, changing the font family, font size and colour used to render them. The following rule will accomplish this:

h1 {
    font-family: sans-serif;
    font-size: 2.4em;
    color: #f00;
}

Here, san-serif is a standard way of referring to the browser’s default sans serif font. You can also name the desired font family explicitly by providing its name in quotes, e.g., "Fira Sans", "Helvetica".

Note also how the size of the font has been specified. 2.4em is a relative size measure, indicating a size 2.4 times larger than the base font size.

Finally, consider how text colour is defined. #f00 is an abbreviation of #ff0000—i.e., a colour with a red component of 0xff (255) and green & blue components of 0. CSS also supports a set of standard colour names, so we could have used red instead here.

Now suppose that our stylesheet also had this rule:

body {
    color: blue;
}

How would this interact with the h1 rule?

Task 2.1

  1. Go to the MDN Playground. Create a small HTML document containing some short paragraphs of text, along with a level 1 heading and a level 2 heading.

  2. Add the h1 style rule described above. Note how the styling of only the level 1 heading changes.

  3. Add the body rule described above. Note how the styling of the rest of the document changes, but h1 remains styled as it was before.

  4. Now modify the body rule so that it changes font size. You should see that this also influences h1, because its style rule sets a font size relative to the base font size.

Further Reading

The MDN website provides a detailed Properties Reference. This site also has in-depth tutorials, e.g., CSS Styling Basics.