Skip to content
Tutorials Center
My learning

Topics

Lesson 2 of 139 ยท Getting Started

Adding CSS to a Page

Learn the three ways to add CSS to HTML (the style attribute, a style element and a linked stylesheet), when to use each, and which one wins in a conflict.

CSS on its own does nothing. It has to be connected to an HTML page before the browser will apply it. There are three ways to make that connection: a style attribute on a single element, a <style> element inside the page, and a separate .css file linked from the page.

All three use exactly the same properties and values. What changes is where the CSS lives, how much of the site it can reach, and how easy it is to maintain. In this lesson you will try each one, learn which to reach for in real projects, and see what happens when they disagree.

Inline styles: the style attribute

The most direct way to style an element is the global style attribute. Its value is a list of declarations, with no selector and no braces, because the element it sits on is the target:

Inline styles

Inline styles are quick, but they have real drawbacks:

  • No reuse. To make ten paragraphs teal, you have to repeat the attribute ten times, and change it in ten places later.
  • Limited features. You can't use selectors, so there is no way to write hover states, style a placeholder, or adapt to screen size with a media query.
  • Very hard to override. Inline declarations beat almost any rule in a stylesheet, which makes them painful to work around later.
  • Mixed concerns. Presentation ends up scattered through your content, so the HTML gets harder to read.

Where inline styles make sense: values that are truly unique to one element, especially ones set by JavaScript or a server template, such as the width of a progress bar or a user's chosen accent color. A neat modern trick is to pass in just a custom property, like style="--progress: 40%", and keep the real styling in your stylesheet. You will see how in Custom Properties.

Internal styles: the <style> element

The <style> element holds a full stylesheet, with selectors and rules, inside the HTML document itself. It normally goes in the <head>:

HTML
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Recipe Box</title>
  <style>
    body {
      font-family: Georgia, serif;
      max-width: 40rem;
      margin: 0 auto;
    }

    h1 {
      color: sienna;
    }
  </style>
</head>
<body>
  <h1>Recipe Box</h1>
  โ€ฆ
</body>
</html>

Because a <style> block uses selectors, one rule can style every matching element on the page. The examples in this course use <style> blocks for exactly that reason: everything fits in one editor.

A style element

The limitation is that a <style> block only affects the page it lives in. A site with fifty pages would need fifty copies, and every change would mean editing them all.

For real websites, CSS usually lives in its own file with a .css extension. Each page links to it from the <head>:

HTML
<head>
  <meta charset="utf-8">
  <title>Recipe Box</title>
  <link rel="stylesheet" href="/css/site.css">
</head>

The file itself contains only CSS, with no <style> tags:

CSS
/* site.css */
body {
  font-family: Georgia, serif;
  max-width: 40rem;
  margin: 0 auto;
}

h1 {
  color: sienna;
}

This is the approach you should use by default, for several reasons:

  • One file styles every page. Change a color once and the whole site updates.
  • Caching. The browser downloads the file once and reuses it on every page the visitor opens, so later pages load faster.
  • Separation. HTML stays focused on content, CSS on presentation, and both are easier to read and review.
  • Tooling. Editors, linters and build tools all work best with standalone .css files.

The href works like any other URL; see File Paths if relative paths are new to you. You can link several stylesheets, and they are applied in the order they appear. The media attribute can limit a stylesheet to certain conditions, for example media="print" for a print-only file.

Keep it in the head. Stylesheets linked in the <head> are loaded before the page is shown, so visitors never see a flash of unstyled content. The browser does wait for them before painting, so keep the CSS you load lean. CSS Performance covers this in depth.

Avoid @import for loading files. CSS has an @import rule that pulls one stylesheet into another. In a plain stylesheet it makes the browser discover files one after another instead of in parallel, which slows pages down. Prefer several <link> elements, or a build tool that combines files. (@import does have a modern use with cascade layers.)

Which one wins?

What if the same element gets different values from different places? Two simple principles cover most everyday cases:

  1. Inline styles beat stylesheet rules. A declaration in a style attribute wins over normal rules in <style> blocks and linked files, regardless of their selectors.
  2. Between stylesheets, later wins when everything else is equal. <style> blocks and <link>ed files are treated the same way. If two rules have equally specific selectors, the one that comes later in the document wins. That's why a <link> placed after a <style> block can override it, and vice versa.
Inline vs internal

Notice the third paragraph. Its inline style only sets font-style, so the stylesheet's color still applies. Remember from the introduction that declarations combine property by property; only properties that actually conflict need a winner.

This is a simplified picture. Specificity (how precise a selector is), !important, and cascade layers all play a part too, and you will learn the full set of rules in How the Cascade Works. For now, "inline beats stylesheets, and later beats earlier" is enough.

Seeing all three together

Here is a single document using every method at once. In a real project you would rarely mix them like this, but it shows how they relate.

All three methods

The <link> here uses a data: URL so the example can work without a real file; normally href points to a .css file. The heading gets its font from the linked stylesheet, but its color from the <style> block that comes after it. Try moving the <link> below the <style> element and run it again: the heading turns slate blue.

The drawbacks of each method

Each method has a real cost. Knowing them helps you justify the rule of thumb below.

Inline styles

  • No reuse. The same declarations must be repeated on every element, and one change means editing many places.
  • Strong specificity. An inline style beats nearly every normal rule in a stylesheet, so later changes need !important or edits to the HTML.
  • No selectors. You cannot write :hover, :focus, ::before, media queries or @keyframes inline. Only plain declarations are allowed.
  • Messy HTML. Content and presentation mix, which makes pages harder to read and to hand over between people.
  • Security policies. A strict Content Security Policy usually blocks inline styles unless it allows them explicitly.

Internal styles (<style>)

  • One page only. Other pages cannot use the rules. Copying them to ten pages leads to ten versions of the same CSS.
  • Not cached separately. The CSS is part of the HTML, so the browser downloads it again with every page view.
  • Larger HTML files, and a harder time finding the rule when the <style> block grows.
  • Limited management. Linting, minifying and sharing tools expect separate files.

External stylesheets (<link>)

  • An extra request. The page waits for the file before it can paint, because CSS blocks rendering. Keep the file small and use the browser cache well (see CSS performance).
  • Caching can show old styles. After a change, visitors may keep the cached file. Give the file a version in its name or query string (styles.css?v=12, or a content hash) so a new version is fetched.
  • A broken link means an unstyled page. A wrong path, a blocked CDN or a failed download leaves the HTML plain, so be careful with paths.
  • Cross-origin files need correct CORS headers when you use features such as fonts from another domain.

The page below shows the first drawback in practice. The same button is styled twice: once inline, where :hover is impossible, and once with a <style> rule.

What inline styles cannot do

Choosing the right method

A practical rule of thumb:

  • External stylesheets for almost everything on a real site.
  • A <style> element for single-page demos, quick experiments, or a small amount of critical CSS that must arrive with the page.
  • The style attribute for one-off values generated by code, ideally passed as custom properties, and for quick tests while debugging.

If you are just starting a new project, create a styles.css file, link it from every page, and keep your CSS there. You will thank yourself when the site grows.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which method is best for styling a website with many pages?

    An external file is written once, cached by the browser and shared by every page, so a single change updates the whole site.
  2. 2. What does a style attribute contain?

    The element itself is the target, so the attribute holds only declarations such as color: teal; padding: 8px;.
  3. 3. Which of these can you NOT do with inline styles?

    Hover states need a selector (:hover), and inline styles have no selectors. The same goes for media queries.
  4. 4. Two rules in the same stylesheet have identical selectors and set different colors. Which color is used?

    When rules are otherwise equal, source order breaks the tie and the later declaration wins.
  5. 5. Where should a <link rel="stylesheet"> normally go?

    Linking stylesheets in the <head> ensures they load before the page is shown, avoiding a flash of unstyled content.

Summary

  • Inline styles (style="โ€ฆ") style a single element. They can't use selectors and are hard to override; keep them for values generated by code.
  • Internal styles (<style>) hold a full stylesheet for one page. Great for demos and single pages.
  • External stylesheets (<link rel="stylesheet" href="โ€ฆ">) are the default for real sites: shared, cached and easy to maintain.
  • Inline declarations beat stylesheet rules; between stylesheets, the later rule wins when selectors are equally specific.
  • Prefer <link> over @import for loading CSS files.

Next: CSS Syntax, where you take a closer look at rules, declarations and what the browser does with mistakes.