3. How to Add CSS

What you will learn

  • The three ways to add CSS to a page
  • When to use each one
  • Which style wins when they disagree

Three ways

Method Where it goes Best for
External A separate .css file, linked with <link> Real websites
Internal A <style> element in the page One-page demos and examples
Inline A style attribute on one element Quick tests only

1. External CSS

Write your CSS in a file such as style.css, then link it from the <head> of every page.

HTML file

<head>
  <link rel="stylesheet" href="style.css">
</head>

style.css file

body {
  background-color: #eaf5ff;
}

h1 {
  color: #082b59;
}

The CSS file contains only CSS, with no <style> tags. This is the best method, because one file styles your whole site and the browser can cache it.

2. Internal CSS

Example

<style>
  body { background-color: lightblue; }
  h1 { color: navy; }
</style>

<h1>Internal CSS</h1>
<p>Styled from the style element.</p>

Output

Internal CSS

Styled from the style element.

Internal CSS only affects the page it is on, which is why every example in this tutorial uses it.

3. Inline CSS

Example

<h1 style="color: crimson; text-align: center;">Inline CSS</h1>
<p>This paragraph is not styled.</p>

Output

Inline CSS

This paragraph is not styled.

Here the declarations sit inside the style attribute and affect that one element only. They are hard to maintain, so avoid them in real projects.

Which style wins?

If several rules style the same property, the browser decides in this rough order:

  1. Inline styles beat internal and external styles.
  2. More specific selectors beat less specific ones (you will learn this in the Selectors lesson).
  3. If everything else is equal, the rule that comes last wins.

Example

<style>
  p { color: blue; }
  p { color: green; }
</style>

<p>Which colour am I?</p>

Output

Which colour am I?

Both rules are equally specific, so the later one (green) wins.

With external files, order matters too. If you link two stylesheets, rules in the second can override the first.

Common mistakes

  • Putting <style> tags inside a .css file.
  • A wrong file path in href, so the stylesheet never loads.
  • Using inline styles everywhere, which makes later changes painful.
  • Forgetting that a later rule can quietly override an earlier one.

Exercise

Using internal CSS, give the page body a light yellow background and make every paragraph dark green.

Show solution
<style>
  body { background-color: lightyellow; }
  p { color: darkgreen; }
</style>
<p>Style me.</p>

Knowledge check

1. Which element links an external stylesheet?

<link>, inside the <head>.

2. Which method is best for a real website?

External CSS.

3. If two equal rules conflict, which wins?

The one that comes last.

Summary

  • CSS can be external, internal, or inline.
  • Use external files for real sites.
  • Inline beats other styles, and later beats earlier when everything else is equal.
Scroll to Top