Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to connect a CSS file to a page

Short answer

Put the styles in a separate file, for example styles.css, and connect it in <head> with a <link> tag:

<head>
  <link rel="stylesheet" href="styles.css">
</head>
<p>Styles from styles.css apply to this page.</p>

One stylesheet is connected on all pages of the site: you edit the design in one place, and the browser downloads the file once and then takes it from the cache.

File paths

  • styles.css — the file is in the same folder as the HTML.
  • css/styles.css — in the css folder next to the HTML.
  • ../styles.css — one level up.
  • /css/styles.css — from the site root, works from any page.

Styles inside the page

Small styles can be written right in the page, in a <style> tag. That is how the examples on this site are made:

<style>
  p { color: steelblue; }
</style>
<p>Styled by the style tag.</p>

If several files are connected, with equal specificity the rule from the one connected lower wins.

Common mistake

The styles do not apply, and no error is visible. Almost always it is a wrong path: the file is called style.css while href says styles.css, or the file is in another folder. Open the developer tools (F12), the Network tab: a file with status 404 was not found by the browser.

Functions used in this recipe

  • <link> — Links an external resource to the page: a stylesheet, the site icon, a font.
  • <style> — Embeds CSS right into the HTML page.
  • <head> — The service part of the page: encoding, tab title, linked styles and scripts.
  • @import — Includes another CSS file into the current one.
  • href — The address an `<a>` link leads to or a `<link>` points at.

Thanks for reading!

Donate to the site — we work hard for you.