An Introduction to CSS

<aside> <img src="/icons/list_purple.svg" alt="/icons/list_purple.svg" width="40px" />

Learning objectives

By the end of this chapter you will:

What is a Stylesheet?

In the context of web development, a stylesheet is a file (or form of code) used to define the look and format of a document written in HTML. The most common type of stylesheet is a Cascading Style Sheet (CSS), which is used to style web pages and user interfaces written in HTML.

A CSS stylesheet contains a set of rules. Each rule specifies how certain elements (identified by selectors like tags, classes, or IDs) on a webpage should be displayed. This can include their layout, colours, fonts, sizes, spacing, and more.

<aside> <img src="/icons/code_lightgray.svg" alt="/icons/code_lightgray.svg" width="40px" />

Er, what’s the deal with the ‘Cascading’ part of the name? ⛲

</aside>

By separating the content (HTML) from the presentation (CSS), stylesheets enable developers and designers to create more flexible, maintainable, and accessible web pages. Changes to the appearance of an entire website can be made by simply editing a single CSS document, without altering the underlying HTML structure.

This is sometimes referred to as the principle of Separation of Concerns.

<aside> <img src="/icons/fire_orange.svg" alt="/icons/fire_orange.svg" width="40px" />

Separation of Concerns? Sounds Boring!

</aside>

Oh boy… what a dry start to the language of design. Now that we've got that out of the way, let's get to the good bits.


CSS Rules

A CSS stylesheet consists of a series of rules that dictate how elements rendered by a web browser should be styled. The basic structure of CSS can be broken down into three main components: selectors, properties, and values. Here’s an overview:

  1. Selectors: These are patterns used to select the elements you want to style. Selectors can target elements by their type (e.g., h1, p), class (e.g., .classname), ID (e.g., #idname), or even more complex patterns like attribute selectors or pseudo-classes (e.g., :hover). Selectors determine which HTML elements the subsequent style rules will apply to.
  2. Properties: Once you've selected an element, properties are used to specify what aspects of the element's styling you want to change. For example, you might want to set the colour, width, height, margin, padding, font size, and so on. Each property defines a specific aspect of styling, like text colour (color), font size (font-size), element background colour (background-color), and many others. Note that words like 'color' are written in US-English.
  3. Values: Values are assigned to properties to specify how you want to style the selected elements. For example, if you're setting the color property, the value could be a colour name (red), a hexadecimal code (#ff0000), an RGB value (rgb(255, 0, 0)), or other colour formats supported by CSS.