Add CSS to a page

Add CSS to HTML

Connect an external stylesheet, use a style element when appropriate, and understand why inline styles are difficult to maintain.

There are three ways to get CSS into a page. You’ll use one of them almost all the time.

An external stylesheet

Put your CSS in its own file and link it from the head of the document:

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

This is the normal way. The CSS lives apart from the content, every page of the site can share the same file, and the browser caches it. Visit a second page and the stylesheet is already there.

The href works like any URL. /styles.css starts from the root of the site. styles.css without the slash is relative to the current page, which breaks as soon as you move the HTML file into a folder. I use the leading slash.

A style element

For a quick experiment, or a single page that will never share its styles, you can write CSS inside a style element in the head:

<style>
  body {
    font-family: system-ui, sans-serif;
  }
</style>

It’s handy when you want to test something in a scratch file. It’s not great for a real site, because you can’t cache it separately and you end up copying it between pages.

Inline styles

You can also attach a declaration directly to one element with the style attribute:

<p style="color: rebeccapurple">Hello</p>

Notice there is no selector here. The style applies to that one paragraph and nothing else.

My advice: avoid inline styles for normal styling. You can’t reuse them, you can’t put them in a shared file, and they are hard to override, because a declaration in a style attribute beats a normal rule from a stylesheet. When you see a lot of inline styles in a project, it’s usually a sign the CSS is hard to change.

Order matters

You can link more than one stylesheet. When two rules are otherwise equal and set the same property, the one that comes later wins.

<link rel="stylesheet" href="/base.css">
<link rel="stylesheet" href="/components.css">

So put broad foundations first, like fonts and colors for the whole page, and more specific component or page styles after them. If a rule mysteriously loses to another, check the order the files are loaded in.

Lesson completed