There are three places you can put CSS. They all work. They are not equally good.
1. Inline CSS
You write the styles inside an element’s style attribute.
<p style="color: green; font-size: 20px;">Styled with an inline style.</p>
It only affects that one element and it beats most other rules. It is handy for a quick test or for a value that is set by code, and awkward for everything else.
2. Internal CSS
You put a <style> element inside the page, normally in the <head>.
<style>
p { color: green; font-size: 20px; }
</style>
<p>Styled with an internal stylesheet.</p>
<p>Every paragraph on this page is affected.</p>
This is good for a single page or a demo. Every example in this course uses it so you can see the HTML and the CSS together.
3. External CSS
You write the CSS in its own file, for example style.css, and link to it from each page.
<head>
<link rel="stylesheet" href="style.css">
</head>
p {
color: green;
font-size: 20px;
}
One file can style every page of a website. The browser also downloads it once and reuses it, which makes later pages load faster.
Which one should you use?
| Method | Good for | Watch out for |
|---|---|---|
| Inline | Quick tests, values set by code | Hard to maintain, hard to override |
| Internal | One page, demos, small experiments | Repeated on every page |
| External | Real websites | One extra file to load |
Rule of thumb
Wrong file path
style.css means the href does not point to the file.Exercise: move a style out
Take <p style="color: green;">Hello</p> and rewrite it so the color comes from a <style> element instead of the attribute.
Show a possible solution
<style>
p { color: green; }
</style>
<p>Hello</p>