mindixx
mindixx

Reference · module 4

First styles

Everything this module explains, on one page.

A CSS rule

Write a CSS rule and connect a stylesheet to a page.

  • CSS decides how HTML looks. A rule is a selector and a block of declarations: p { color: navy; } makes every paragraph navy.
  • Each declaration is a property, a colon, a value and a semicolon: font-size: 18px; A rule can hold many declarations, one per line, inside the same braces.
  • Styles usually live in a separate file linked from the head: <link rel="stylesheet" href="style.css">. One file can then style every page of the site.

The mistake you are about to make

p { color = red }

p { color: red; }

Assigning a value looks like = everywhere else, including HTML attributes. CSS uses a colon between property and value, and a semicolon after.

Selectors

Target elements by tag, class and id.

  • An element selector styles every element of that kind: h2 { } applies to all h2 headings on the page. It is the broadest kind of selector.
  • A class selector starts with a dot and styles elements with that class: .price { } matches <span class="price">. Many elements can share a class.
  • An id selector starts with #: #cart { } matches the one element with id="cart". In practice classes are preferred for styling, because they can be reused.

The mistake you are about to make

price { color: red; }

.price { color: red; }

In HTML the class is written plain, class="price", so the selector seems to be just the word. Without the dot CSS looks for a <price> tag, which does not exist.

Colour and text

Set colours, font sizes and alignment.

  • color sets the text colour and background-color sets the fill behind it. Values can be names like tomato or hex codes like #1e90ff.
  • font-size needs a unit. px is a fixed pixel size; rem is relative to the root font size, so 1.5rem is one and a half times the base and respects the user's settings.
  • text-align: center centres text inside its box; left and right do the obvious. It aligns the text inside the element, not the element on the page.

The mistake you are about to make

font-size: 18;

font-size: 18px;

In HTML attributes and many languages a bare number is fine. CSS ignores a size without a unit, so the declaration silently does nothing.

Back to the map