Command Palette

Search for a command to run...

Hectal
PHASE 0Beginner ~26 min· topic 2 of 4

Topic 0.2

Three Ways to Add CSS

In one line

CSS can go in a style attribute on one element, in a <style> element in the page, or in a separate .css file linked with <link rel="stylesheet">; external files are the normal choice, and when they conflict, inline styles beat rules, and between rules the more specific, then the later, wins.

Think of it like this

Rules for a school. A note pinned to one student's shirt ("Ravi: wear a cap today") is an inline style: it only affects that one student and overrides the general rules. A notice on one classroom's board is a <style> element: it applies to that room only. The school rulebook that every classroom shares is an external stylesheet: change it once and every room follows.

Words you'll meet

New words in this topic, in plain English. Come back here whenever one feels fuzzy.

Attribute
Extra information written inside an HTML opening tag, like href="..." or style="...".
Inline style
CSS declarations written in an element's style attribute. They affect only that element.
`<style>` element
An HTML element, usually in the head, that contains CSS rules for that page.
External stylesheet
A separate .css file that pages connect to with <link rel="stylesheet">.
`<link>`
An element in the head that connects the page to another file, such as a stylesheet.
Cache
The browser's saved copies of files, so it doesn't download the same file again on the next page.
Document order
The order in which things appear in the HTML, from top to bottom.
`@import`
A CSS command that loads another stylesheet from inside a stylesheet. Slower than <link>.

Step by step

01Inline: style one element

Put declarations straight into the style attribute. Only this paragraph turns red. To make ten paragraphs red you'd repeat it ten times, which is the main problem with inline styles.

index.htmlwhole filehtml
<p style="color: red; font-weight: bold">Only I am red.</p>

02A <style> element: style the whole page

Move the CSS into a <style> element in the head and use a selector. Every paragraph on this page is now styled by one rule. Other pages of your site don't see it.

index.htmlwhole filehtml
<head>
  <meta charset="utf-8">
  <title>My page</title>
  <style>
    p { color: red; }
  </style>
</head>

03An external file: style every page

Move the rules into style.css and link it from the head of every page. Change the file once and the whole site changes. The browser downloads it on the first page and reuses its cached copy on the others.

index.htmlwhole filehtml
<head>
  <meta charset="utf-8">
  <title>My page</title>
  <link rel="stylesheet" href="style.css">
</head>

04Organise the folder

A common layout keeps styles in a css folder. The href is a path from the HTML file to the CSS file, so from index.html it is css/style.css. Paths inside the CSS file (for example a background image with url(...)) are relative to the CSS file, not the page.

my-site/whole filetext
my-site/
  index.html        <link rel="stylesheet" href="css/style.css">
  about.html        <link rel="stylesheet" href="css/style.css">
  css/
    style.css       background: url("../images/bg.png");
  images/
    bg.png

05Decide who wins

If all three set color on the same paragraph, the inline style wins. Between the <style> element and the linked file, compare selectors first; if they're equally specific, whichever comes later in the HTML wins.

Decide who winsdiagram
Rendering diagram…

Try it yourself

  1. 1

    Swap the link order

    In the second example, move the <link> line above the <style> element. Predict the colour of the first heading, then run. The console should now print rgb(255, 165, 0) (orange).

  2. 2

    Out-specify the order

    Swap them back so the link is last again. Now change the <style> rule to body h1 { color: orange; }. Predict: does order still decide? (No: body h1 is more specific, so orange wins even though it comes first.)

  3. 3

    Refactor an inline style

    In the first example, remove style="color: crimson" from the third paragraph, give it class="from-inline", and add a .from-inline { color: crimson; } rule to the <style> element. The page looks the same, but the style now lives with the rest of the CSS.

Code & diagrams

All three ways on one page New tab

The preview can't load other files, so the `<link>` uses a `data:` URL that contains the CSS text itself. It behaves exactly like a separate file.

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

rgb(46, 139, 87)
rgb(102, 51, 153)
rgb(220, 20, 60)
Stylesheets on this page: 2
Who wins: order and inline styles New tab

The `<link>` comes after the `<style>`, so its equally specific `h1` rule wins. Swap the two lines in the head and run again: now orange wins.

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

first h1: rgb(70, 130, 180)
second h1: rgb(0, 128, 0)
Inline styles can't do everything New tab

Hover over both buttons. A `style` attribute has no selector, so it can't say "when hovered". The class version can.

Preview

Press Run to see the page.

Console

Nothing logged yet.

Break it on purpose

Errors are the best teachers. Make each change, read the error, guess what went wrong, then reveal the answer.

Break #1

Link to a file that isn't there

In a local project, write <link rel="stylesheet" href="styles.css"> when the file is really called style.css.

terminal
$ DevTools → Console
── what you'll see ──
GET http://localhost:3000/styles.css net::ERR_ABORTED 404 (Not Found)

Break #2

Serve CSS with the wrong type

A misconfigured server sends style.css with the header Content-Type: text/html (often because it served an HTML error page instead).

terminal
$ DevTools → Console
── what you'll see ──
Refused to apply style from 'http://localhost:3000/style.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.

Myth vs fact

Myth

A <style> element always beats an external stylesheet because it's "closer" to the page.

Fact

They have exactly the same strength. Specificity decides first; on a tie, whichever comes later in the document wins.

Myth

Inline styles are faster because the browser doesn't download anything.

Fact

They add bytes to every page, can't be cached separately, and are repeated on every element. One cached stylesheet is usually faster across a site.

Myth

@import is a tidy way to split CSS into files.

Fact

It is tidy to write but slow to load, because each import is discovered only after its parent file arrives. Use several <link> elements or a build step that bundles files.

Pro corner

Extra depth for experienced readers. New to this? Skip it for now and come back later.

  • ▸

    A <link rel="stylesheet"> with a media attribute that doesn't match (for example media="print") is still downloaded, but at low priority and without blocking rendering. That's the basis of some non-critical CSS loading tricks.

  • ▸

    A strict Content Security Policy (a security header that limits what a page may load) often forbids inline styles (style-src without 'unsafe-inline'). External stylesheets keep you compatible with it; this is one more reason to avoid style attributes in production.

  • ▸

    JavaScript that sets element.style.color = "red" writes an inline style. That's why styles set from scripts beat your stylesheet, and why toggling a class (element.classList.add("active")) is usually the better habit (see the /javascript course, The DOM).

  • ▸

    url() values inside a stylesheet resolve relative to the stylesheet's own URL. A <style> element's URLs resolve relative to the page. Moving CSS from one to the other can break image paths.

Remember this

  1. 1

    Inline styles use the style attribute (extra information written inside an HTML tag) directly on one element: <p style="color: red; font-size: 20px">. There is no selector and no braces, only declarations. It styles that single element and nothing else. It can't express hover effects, screen-size rules (media queries) or anything that needs a selector, and it mixes looks into your content, so it is hard to maintain.

  2. 2

    The **<style> element** holds normal CSS rules inside the HTML page, usually in the <head>: <style> p { color: red; } </style>. Its rules apply to the whole page they're in, but no other page. It's handy for single-page demos, emails' fallback styles, and small critical CSS that must arrive with the HTML.

  3. 3

    An external stylesheet is a separate file, such as style.css, connected from the <head> with <link rel="stylesheet" href="style.css">. rel="stylesheet" says what the linked file is; href is its path, relative to the HTML page (the same path rules you learned for links and images). Every page that links the file shares it, and the browser caches (keeps a saved copy of) it, so moving between pages doesn't download it again. This is how real sites are built.

  4. 4

    When the three disagree, here's who wins. An inline style beats any rule in a <style> element or stylesheet, however specific its selector (the only thing that beats it is a rule marked !important, which you'll meet in Phase 2). A <style> element and a <link>ed file are equal: neither type wins by itself. Their rules compete on specificity, and on a tie the one that appears later in the document wins.

  5. 5

    That makes link order matter. Sites often load a base or reset stylesheet first and their own theme after it: <link href="reset.css"> then <link href="theme.css">. If you swap them, the reset's rules come later and undo your theme wherever the selectors are equally specific.

  6. 6

    There is a fourth door you should know about but rarely use: @import url("other.css"); at the very top of a stylesheet pulls in another stylesheet. The browser only discovers the imported file after downloading and reading the first one, so imports load one after another and slow the first paint. Prefer several <link> elements, which download in parallel, or a build tool that joins files into one.

Explain it without notes

01

What are the three ways to add CSS to a page, and when would you use each?

02

A paragraph matches p { color: blue; } in a linked file and p { color: red; } in a <style> element. Which colour wins?

03

Why do professional sites use external stylesheets instead of inline styles?

04

Why is @import slower than <link>?

Practice

01

Write the <head> of a page titled Shop that links two stylesheets, css/reset.css and css/theme.css, in the order where the theme can override the reset.

02

Rewrite this inline style as a class in a <style> element: <p style="color: gray; font-style: italic">Note</p>.

03

A page has <style>h2 { color: red; }</style> and then <h2 style="color: blue">. What colour is the heading, and why?

Trade-offs

  • ↔

    External stylesheets cost one extra request on the first page view but are cached afterwards; inlining a small amount of critical CSS in a <style> element can make the very first paint faster, at the cost of sending those bytes with every page.

  • ↔

    Inline styles are convenient for one-off values set by JavaScript (like a progress bar's width), but they are hard to override and impossible to reuse; keep them for truly dynamic values.

Done when you can

  • I can add CSS with a style attribute, a <style> element and a linked .css file.

  • I can write a correct <link rel="stylesheet" href="..."> with a relative path.

  • I know an inline style beats normal rules, and that <style> and <link> are equal in strength.

  • I can predict which of two equal rules wins from their order in the document.

  • I can find a missing stylesheet in the Network tab.