Chapter 02 of 33

Adding CSS to HTML

In the previous chapter, Introduction to CSS, we wrote our first rules inside a <style> tag. But that is only one of the ways to connect CSS with an HTML page.

There are three main ways to add CSS to HTML — inline, internal and external — plus the @import rule for loading one style sheet from another. Each has its own use, and choosing the right one affects how maintainable and how fast your website is. Let's look at each in turn.


The Three Ways at a Glance

MethodWhere the CSS livesApplies to
Inline CSSIn the style attribute of one elementOnly that element
Internal (embedded) CSSIn a <style> element, normally in the <head>Only that one HTML page
External CSSIn a separate .css file linked with <link>Every page that links to the file

1. Inline CSS

Inline CSS is written directly inside an HTML element using the style attribute. It contains only declarations — there is no selector and no curly braces, because the element itself is the target.

<h1 style="color: crimson; text-align: center;">Results Announced</h1>
<p style="font-size: 18px;">Check your marks below.</p>
<p>This paragraph has no inline style.</p>

Output:

Results Announced              ← crimson, centred
Check your marks below.        ← 18px
This paragraph has no inline style.   ← browser default style

When is inline CSS useful?

  • Quick experiments and testing.

  • HTML emails — many email clients strip <style> blocks, so styles are inlined.

  • Values set by JavaScript at runtime, for example element.style.width = "70%" for a progress bar. (JavaScript writes to the same style attribute.)

Why you should avoid it for normal styling

  • No reuse: the style must be repeated on every element. Ten red headings = ten copies.

  • Mixes content with presentation — exactly the problem CSS was invented to solve.

  • Very hard to override: inline declarations beat any normal rule in a style sheet, no matter how specific its selector is. (The details are in Specificity, Inheritance & the Cascade.)

  • Limited: you cannot write hover effects (:hover), media queries, or pseudo-elements like ::before inline, because those need a selector or an at-rule.


2. Internal (Embedded) CSS

Internal CSS is written inside a <style> element in the HTML document itself, usually in the <head>. Its rules apply only to that page.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Internal CSS</title>
  <style>
    body {
      font-family: Arial, sans-serif;
    }

    h1 {
      color: teal;
    }

    p {
      color: #444444;
      line-height: 1.6;
    }
  </style>
</head>
<body>
  <h1>Semester Timetable</h1>
  <p>Classes begin at 9:00 AM.</p>
  <p>Labs are on Wednesday and Friday.</p>
</body>
</html>

Output: the heading is teal, and both paragraphs get the grey colour and line spacing from the single p rule.

When to use internal CSS

  • A single-page project, a demo, or a practice file.

  • Styles that are truly unique to one page.

  • Small amounts of "critical CSS" that performance-focused sites inline in the <head> so the top of the page can render without waiting for an extra file.

The drawback: if you have 20 pages, you would have to copy the same <style> block into all 20, and the browser cannot cache it separately — it is downloaded again with every page.

Note on placement: put <style> in the <head>. Browsers will apply a <style> placed lower in the page too, but the content above it may first be drawn unstyled and then jump when the styles arrive.


3. External CSS

External CSS is written in a separate file with a .css extension and connected to HTML pages using the <link> element. One file can style an entire website.

Step 1: Create styles.css. It contains only CSS — no <style> tags and no HTML.

/* styles.css */
body {
  font-family: Arial, sans-serif;
  margin: 24px;
}

h1 {
  color: navy;
}

p {
  color: #333333;
}

Step 2: Link it from the <head> of every page that needs it.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Home</title>
  <link rel="stylesheet" href="styles.css">
</head>
<body>
  <h1>CS Learning Portal</h1>
  <p>Free tutorials for every subject.</p>
</body>
</html>

Breaking down the <link> element:

AttributeMeaning
rel="stylesheet"The relationship: "this linked file is a style sheet for this page". Required — without it the CSS is not applied.
href="styles.css"The path or URL of the CSS file.
media="..." (optional)Apply the file only when a media query matches, e.g. media="print".

You may see old code with type="text/css". It is unnecessary in modern HTML because CSS is the default; you can leave it out.

Getting the path right

Most "my CSS is not working" problems are wrong paths. The href is resolved relative to the HTML file:

project/
├── index.html
├── about/
│   └── team.html
└── css/
    └── styles.css
Linking fromCorrect href
index.htmlcss/styles.css
about/team.html../css/styles.css (go up one folder first)
Any page on a deployed site/css/styles.css (root-relative: starts from the site root)

Note that a root-relative path like /css/styles.css does not work when you open the file directly from disk (file:///...), because "/" then means the root of your drive. Use relative paths for local practice, or run a small local server.

Why external CSS is the standard choice

  • One file, whole site: change a colour once; every page updates.

  • Caching: the browser downloads styles.css once and reuses it from its cache on every other page, so later pages load faster.

  • Clean separation: HTML files stay readable; designers and developers can work on different files.

Linking more than one style sheet

<head>
  <link rel="stylesheet" href="css/reset.css">
  <link rel="stylesheet" href="css/layout.css">
  <link rel="stylesheet" href="css/print.css" media="print">
</head>

The files are applied in the order they appear. If two rules with equally specific selectors set the same property, the one that comes later wins — so general files (like a reset) go first and specific files go last. The print.css file is used only when the page is printed (or saved as PDF).


4. The @import Rule

A CSS file can load another CSS file with @import:

/* styles.css */
@import url("base.css");

h1 {
  color: blue;
}

Rules:

  • @import must appear at the top of the style sheet, before any other rules (only @charset and @layer statements may come before it). An @import placed after a normal rule is ignored.

  • The imported rules behave as if they were written at the position of the @import, i.e. before the rest of the file.

  • It can also be used inside a <style> element, with the same "must come first" rule.

With two <link> tags:              With @import inside styles.css:

  HTML ─┬─► base.css                  HTML ──► styles.css ──► base.css
        └─► styles.css                          (download 1)     (download 2,
     (both downloaded in parallel)                               starts only after
                                                                 styles.css arrives)

The browser discovers an imported file only after it has downloaded and parsed the file containing the @import. This creates a chain of sequential downloads and delays rendering. With multiple <link> elements, the browser sees all files immediately and fetches them in parallel. (Build tools such as bundlers and preprocessors also combine imports into one file for production, so the slowdown is avoided.)


Which Style Wins When Methods Are Mixed?

Let's test a page that uses all three methods on the same element. Create these three files in one folder.

base.css:

body {
  background: #eeeeff;
  font-family: Arial, sans-serif;
}

p {
  font-size: 22px;
}

styles.css:

@import url("base.css");

h1 {
  color: blue;
  font-family: Georgia, serif;
}

p {
  color: purple;
}

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Mixing methods</title>
  <link rel="stylesheet" href="styles.css">
  <style>
    h1 {
      color: green;
    }
  </style>
</head>
<body>
  <h1>Heading</h1>
  <h1 style="color: red;">Inline wins</h1>
  <p>Paragraph from external file.</p>
</body>
</html>

Output:

Heading                        ← GREEN, Georgia font
Inline wins                    ← RED, Georgia font
Paragraph from external file.  ← purple, 22px
(page background is light lavender, from base.css)

Step-by-step reasoning:

  1. The first h1 matches two rules that set color: blue from styles.css and green from the <style> block. Both selectors are just h1 (equal specificity), so source order decides. The <style> element comes after the <link>, so green wins.

  2. The font-family: Georgia from the external file is not lost. Rules don't replace each other as a whole; the cascade is decided per property. Only color was in conflict.

  3. The second h1 has an inline style, which beats both style-sheet rules, so it is red (but still Georgia).

  4. The paragraph gets font-size: 22px from the imported base.css and color: purple from styles.css.

A very common misunderstanding is that "internal CSS always beats external CSS". That is false. Internal and external style sheets have the same priority; whichever comes later in the document wins (for equal specificity). If we moved the <style> block above the <link>, the first heading would turn blue.

The general priority for normal (non-!important) declarations is:

Inline style attribute
        ▲ beats
Style sheet rules (internal <style> and external <link> are equal;
        ▲ beats   compare specificity, then later-in-source wins)
Browser default styles

The full algorithm, including !important and cascade layers, is explained in Specificity, Inheritance & the Cascade.


Comparison Table

FeatureInlineInternalExternal
Syntaxstyle="..." attribute<style> element.css file + <link>
ScopeOne elementOne pageMany pages
ReusabilityNoneWithin the pageAcross the site
Browser cachingNoNo (part of the HTML)Yes
Selectors, :hover, media queriesNot possibleYesYes
Extra HTTP requestNoNoYes (one per file, then cached)
Best forJS-driven values, emails, quick testsSingle pages, demos, critical CSSReal websites (default choice)

Common Mistakes

  • Missing rel="stylesheet": <link href="styles.css"> loads nothing.

  • Wrong path: check the Network tab in DevTools — a 404 next to styles.css means the browser could not find the file.

  • HTML inside the CSS file: writing <style> ... </style> inside styles.css breaks the first rule. A .css file contains only CSS.

  • Using src on <link>: <link rel="stylesheet" src="styles.css"> loads nothing — <link> uses href (src belongs to <script> and <img>). Also remember it is a void element: write <link ...> with no closing </link> tag.

  • Putting @import after other rules: it will be ignored.

  • Writing selectors in a style attribute: style="p { color: red; }" is invalid; inline styles contain declarations only.

  • Browser cache confusion: after editing the CSS on a live site, the browser may show the old cached file. Do a hard reload (Ctrl+Shift+R) while developing.


Interview / Exam Questions

1. What are the different ways to add CSS to an HTML document?

Inline CSS (the style attribute on an element), internal CSS (a <style> element in the document), and external CSS (a separate .css file linked with <link rel="stylesheet" href="...">). A style sheet can also pull in another style sheet with @import.

2. Which has higher priority: internal or external CSS?

Neither inherently. Both are author style sheets with equal priority. If their selectors have the same specificity, the rule that appears later in the document wins. Inline styles beat both (for normal, non-!important declarations).

3. Why is external CSS preferred for large websites?

It is written once and reused across all pages, so maintenance is easy; the browser caches the file, so subsequent pages load faster; and it keeps HTML clean by separating content from presentation.

4. Why is @import discouraged compared with <link>?

An imported file is discovered only after the importing style sheet has been downloaded and parsed, so the downloads happen one after another and delay rendering. Multiple <link> elements are discovered immediately and downloaded in parallel.

5. Can you write a :hover style using inline CSS?

No. The style attribute holds only declarations for that element; pseudo-classes, pseudo-elements and media queries need a selector or an at-rule, which are only possible in a style sheet (internal or external).

6. A page has <style>p { color: green; }</style> and then <link rel="stylesheet" href="a.css">, where a.css contains p { color: blue; }. What colour are the paragraphs?

Blue. The selectors have equal specificity, and the rule from a.css comes later in the document order, so it wins.


Summary

  • Inline: style attribute, one element, highest normal priority, no reuse — use sparingly.

  • Internal: <style> in the <head>, one page — good for demos and single pages.

  • External: .css file linked with <link rel="stylesheet" href="..."> — the default for real websites because it is reusable and cacheable.

  • @import must come first in a style sheet and causes sequential downloads; prefer <link>.

  • Internal and external CSS are equal in priority; with equal specificity, later wins. The cascade works per property.

Now that we know where CSS goes, the next chapter, CSS Selectors, shows how to target exactly the elements we want to style.