Hone

Lessons · HTML and CSS · attaching CSS

Attaching CSS

CSS reaches a page three ways: a linked stylesheet file, a style element in the page, or a style attribute on one element. The attribute wins over both, and cannot be reused.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

Knowing where a style comes from is half of debugging. A colour that will not change is usually an inline style or a later file you did not know was loaded.

How to think about it

One linked file for the site. A style element for a one-page demo. An inline style almost never, because the next person cannot override it from the stylesheet.

Worked example

<link rel="stylesheet" href="style.css">
In the head: one shared file, cached once, used by every page.
<style> p { color: rgb(0, 128, 0); } </style>
A style element: CSS inside the page. Fine for one page or a demo.
<p style="color: rgb(200, 0, 0)">Inline</p>
A style attribute on one element: it beats the stylesheet, and no rule can reuse it.
<p>Shared</p>
This paragraph takes the style element's green; the inline one stays red.

Your turn

Attach the site's stylesheet.

<link rel="stylesheet" ="site.css">

The trap

Fixing a colour with an inline style because the stylesheet 'did not work'. It works; something more specific was winning, and inline hides that instead of fixing it.

Next in HTML and CSS

Every HTML and CSS lesson on one page

Practise attaching CSS on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.