In the previous lesson you linked css/styles.css to every page of The Blue Cup. But throughout the course you've seen two other ways of writing CSS: the style attribute, which you used to draw temporary borders in Block and Inline Elements: div and span, and the <style> element, which has held the menu's styles until now. In this lesson you'll compare the three approaches (inline, internal and external), learn in which specific cases each one makes sense and, above all, understand what happens when several rules try to style the same element. That mechanism, the cascade, is the "C" in CSS and the cause of most "why isn't my style being applied?" moments. By the end, the site will have no scattered styles and the stylesheet will be organised for the rest of the module.
Contents
- Three ways to apply CSS
- Inline CSS: the
styleattribute - Internal CSS: the
styleelement - External CSS: the linked stylesheet
- Comparison
- When each approach is acceptable
- The cascade: when rules compete
!importantand why to avoid it- Project: all the styles in
styles.css
Three ways to apply CSS
All three approaches use the same properties and values; what changes is where the CSS is written and, therefore, how many elements and pages it reaches:
graph LR
A["Inline CSS<br/>style attribute"] -->|"one element"| E["A specific element"]
B["Internal CSS<br/>style element in the head"] -->|"one page"| P["Every element<br/>on that page"]
C["External CSS<br/>.css file + link"] -->|"the whole site"| S["Every page<br/>that links it"]
Inline CSS: the style attribute
The global style attribute contains declarations (with no selector and no braces) that apply only to the element carrying it:
- There's no selector: the "selector" is implicitly the element itself.
- Declarations are separated by semicolons, just as inside braces.
- You can use single quotes inside if a value needs them:
style="font-family: 'Georgia', serif;".
Its limitations are significant:
- It can't be reused: if ten paragraphs need that look, the attribute is repeated ten times.
- It doesn't support pseudo-classes or pseudo-elements: you can't write a
:hoveror a::beforeinline. - It doesn't support media queries: it can't adapt to the screen size or to printing.
- It mixes content and presentation on the same line, exactly the opposite of the principle you saw in the previous lesson.
- It beats almost everything in the cascade, as you'll see shortly, so it's hard to change from the stylesheet afterwards.
Internal CSS: the style element
The <style> element goes in the head and contains complete rules (selectors and declarations), just like a .css file:
<head>
<meta charset="utf-8">
<title>Menu | The Blue Cup</title>
<style>
caption {
color: #1f4e79;
font-weight: bold;
}
</style>
</head>- It affects the whole page it's on, but no other.
- It supports everything an external stylesheet does: pseudo-classes, media queries, comments…
url()paths are worked out from the page (there's no CSS file).- It doesn't require an extra download: the CSS arrives with the HTML itself.
That's what you did in Styling Tables: a convenient solution for one page, but one that forces you to copy the block if another page needs the same styles (as you discovered in exercise 2 of that lesson).
External CSS: the linked stylesheet
This is the approach you already know from the previous lesson: a .css file linked with <link rel="stylesheet">.
- It affects every page that links it.
- It's downloaded once and stays in the cache.
- It concentrates the design in a single file, completely separate from the content.
Comparison
| Criterion | Inline (style="…") |
Internal (<style>) |
External (<link>) |
|---|---|---|---|
| Where it's written | In an attribute on each element | In the head of each page |
In a separate .css file |
| Scope | One element | One page | Every page that links it |
| Reuse | None | Within the page | Across the whole site |
| Maintenance | Very difficult: you have to search element by element | Difficult if repeated across several pages | Easy: a single file |
| Pseudo-classes and media queries | No | Yes | Yes |
| Cache | No (comes with the HTML) | No (comes with the HTML) | Yes, reused between pages |
| Priority in the cascade | Very high: beats any selector | Normal: competes on specificity and order | Normal: competes on specificity and order |
| Use at The Blue Cup | No | No | Always |
A detail in the last row that often surprises people: an internal stylesheet doesn't have higher priority than an external one just because it's internal. Both are "author CSS" and compete under the same rules; what decides, when the selectors are equal, is which one appears later in the document. If the <style> comes after the link, the <style> wins; if it comes before, the link wins.
When each approach is acceptable
The project's general rule is all CSS in the external stylesheet. But there are real situations in which the other approaches make sense:
| Situation | Approach | Why |
|---|---|---|
| HTML emails (for example, The Blue Cup's monthly newsletter) | Inline | Many email programs ignore or strip out <style> blocks and don't load external stylesheets. Newsletters are designed with tables and inline styles, often generated by tools that convert rules into attributes automatically |
| Prototypes and quick tests | Internal (or the Styles pane) | To try out an idea on a single page without touching the shared stylesheet. Once it works, it's moved to the stylesheet |
| Critical CSS | Internal | A performance technique: the few styles needed to paint what's seen first are embedded in a <style>, and the rest is loaded with link. It requires tools and measurement; it gets a mention in Performance and Resource Loading |
| Values calculated by JavaScript | Inline | A script that, for example, moves an element according to the mouse position writes to element.style. It's dynamic: it can't live in a stylesheet |
| Standalone generated pages (an exported report, a server error page) | Internal | A single self-contained file with no dependencies |
| A normal website | External | Everything else |
Notice that almost all the exceptions respond to a technical constraint (email doesn't load stylesheets, the script calculates values on the fly), not to convenience. "It was quicker to put it inline" isn't one of them.
The cascade: when rules compete
Imagine this HTML on the home page:
and these rules spread across the stylesheet:
What colour is the paragraph? Two color declarations target the same element. The browser resolves the conflict with the cascade, a procedure that compares the declarations in this order until one wins:
graph TD
A["Several declarations of the same property<br/>for the same element"] --> B{"1. Any with !important?"}
B -->|"Yes"| G1["The important one wins"]
B -->|"No, or they tie"| C{"2. Origin: browser or author?"}
C -->|"Different"| G2["Author CSS wins<br/>(yours)"]
C -->|"Same"| D{"3. Inline style?"}
D -->|"Yes"| G3["The style attribute wins"]
D -->|"No"| E{"4. Selector specificity"}
E -->|"Different"| G4["The more specific one wins"]
E -->|"Equal"| F["5. Order: the one that appears later wins"]
Let's look at each criterion with examples.
Origin: the browser versus you
Every browser has its own default stylesheet (the "user agent stylesheet" you saw in the Styles pane): it's what makes h1 elements large and links blue and underlined. Any rule of yours for the same property replaces it, even if your selector is simpler. That's why a { color: #1f4e79; } is enough to change the blue of every link.
Basic specificity
When two of your rules compete, the browser looks at which selector is more specific, that is, how precisely it pinpoints the element it targets. From lowest to highest:
| Selector type | Example | Weight |
|---|---|---|
| Type selector (tag) | p |
Low |
| Class, attribute or pseudo-class selector | .notice, [scope="row"], :hover |
Medium |
| ID selector | #allergen-notice |
High |
Inline style attribute |
style="…" |
Higher than any selector |
In the example, .notice is more specific than p, so the paragraph is blue, even if the p rule came later. You already took advantage of this in Styling Tables: .price aligns to the right even though th, td says text-align: left. You'll see the exact calculation of specificity, with combined selectors, in the next lesson.
Order of appearance
If two rules have the same specificity, the one that appears later wins:
The notice will be shown in the second colour. Order counts all the way through: first the stylesheets in the order of their link elements, and within each stylesheet, from top to bottom. That's why the organisation of the stylesheet matters: general things first, specific things after.
The style attribute beats almost everything
Although the ID selector is the strongest, the paragraph is red: the style attribute outranks any selector. This is the big practical problem with inline CSS: if tomorrow you want to change that colour from the stylesheet, you won't be able to (except with !important, which is worse). The style is "nailed" into the HTML.
Inheritance isn't the cascade
There's a different mechanism that you shouldn't confuse with it. Some properties, mainly text ones (color, font-family, font-size, line-height), are inherited: if you give them to an element, its descendants receive them unless a rule of their own says otherwise. Others, such as border, padding or background-color, aren't inherited.
All the paragraphs and the address in the footer will have blue text (inheritance), but only the footer will have the border (it isn't inherited). And any rule that targets a descendant directly, however weak its selector, beats an inherited value. You'll make a lot of use of this in this module: giving the typography to the body once and letting it reach the whole page.
!important and why to avoid it
Adding !important at the end of a value makes that declaration jump ahead of all the normal ones, regardless of specificity or order (even the style attribute):
It looks like a magic fix for "my style isn't being applied", but it's a trap:
- It breaks the reasoning of the cascade: looking at the selector and the order is no longer enough to know what applies.
- It scales badly: to beat an
!importantyou need another!importantwith more specificity or further down. That's how stylesheets end up with dozens of them, where nobody knows what takes precedence. - It hides the real problem: almost always, what's wrong is a selector that's too weak, a rule in the wrong order or a forgotten inline style. DevTools tells you which: in the Styles pane, the losing declaration appears struck through, and the winning one, above it.
There are legitimate and very specific uses: neutralising inline styles in someone else's code that you can't touch (for example, a third-party component) or guaranteeing that a basic utility always works (you'll see a case involving the hidden attribute in The Box Model). Apart from that, at The Blue Cup we won't use !important.
Project: all the styles in styles.css
- Look for scattered styles
Use VS Code's Find in Files (Ctrl + Shift + F) in the the-blue-cup folder with these searches:
| Search for | What you find | What to do |
|---|---|---|
style=" |
Inline styles | Move them into a rule in the stylesheet (with a class if needed) and delete the attribute |
<style |
Internal blocks | Move their rules into the stylesheet and delete the block |
@import |
Chained loads | Replace with link |
You'd expect <style to return no results (you emptied it in the previous lesson), and style=" none either, if at the end of Block and Inline Elements: div and span you removed the test borders you put on the div elements, as the lesson told you to. If any remain, for example:
just delete it: it was a temporary visual aid, and you'll give the offer its final look from the stylesheet, using the featured class it already has, in The Box Model.
There are three cases that aren't scattered styles and should stay as they are:
- The
widthandheightattributes ofimg,video,iframeandcanvas: they aren't decoration, but the dimensions of the resource, which the browser uses to reserve the space before loading it (you saw this in Adding Images). - The
fill,strokeorstroke-widthattributes of the SVG icon in the footer: they're part of the drawing, like the path. What's more, it usescurrentColor, so its colour will be decided by the stylesheet through the footer'scolorproperty. - The colours that the "Most ordered" chart script assigns in
canvas: a canvas is painted with JavaScript, not with CSS.
- Organise the stylesheet
A stylesheet that's going to grow needs a predictable order. The cascade favours general things first and specific things after: broad rules (the body, links) at the top; specific components (the card, the table, the form) further down, where their order lets them refine what came before.
Replace the header comment in styles.css with this one, which includes a table of contents, and set up the section headings. The table rules you already have go into section 7:
/* ==========================================================
The Blue Cup · Main stylesheet
Linked from every page with:
<link rel="stylesheet" href="css/styles.css">
Contents
1. Variables
2. Base
3. Typography and links
4. Header and menu
5. Structure: main, sections and footer
6. Components: card, offer and reviews
7. Tables
8. Forms and buttons
9. Gallery
========================================================== */
/* ---------- 1. Variables ---------- */
/* ---------- 2. Base ---------- */
/* ---------- 3. Typography and links ---------- */
/* ---------- 4. Header and menu ---------- */
/* ---------- 5. Structure: main, sections and footer ---------- */
/* ---------- 6. Components: card, offer and reviews ---------- */
/* ---------- 7. Tables ---------- */
table {
border-collapse: collapse;
/* … the rest of the table rules, unchanged … */
}
/* ---------- 8. Forms and buttons ---------- */
/* ---------- 9. Gallery ---------- */The empty sections will be filled in over the coming lessons. Whenever a lesson asks you to add rules, it will say which section they go in.
- Watch the cascade live
Try this experiment to see the cascade in action, and undo it when you've finished:
-
In
menu.html, temporarily addstyle="color: red;"to thecaptionof the price table. -
Open the page: the title is red. In the Styles pane, you'll see
element.style { color: red; }at the very top and, further down, thecolor: #1f4e79declaration fromstyles.cssstruck through. -
Remove the attribute. Now, in section 7 of the stylesheet, straight after the
captionrule, add:caption { color: green; }Green wins: same specificity, appears later.
-
Move that rule before the original
captionrule: blue wins again. -
Delete the test rule.
- The project convention
The convention is now set: at The Blue Cup there are no style attributes or <style> elements; all the CSS lives in css/styles.css, organised in sections from general to specific, and !important isn't used (with the sole exception you'll see in The Box Model). The reasons, in short: a single place to change the design, a cache shared between pages, clean HTML and a predictable cascade.
Common Mistakes and Tips
- Believing that the internal
<style>always beats the external stylesheet: it doesn't. When the selectors are equal, order in the document decides. - Fixing a style that "isn't being applied" with
!important: first, open the Styles pane and look for what's striking it through and why. - Leaving inline test styles after debugging: search for
style="before calling a page finished. - Confusing inheritance and the cascade: if the text colour of a paragraph doesn't change when you give
colorto itssection, a rule is probably targeting the paragraph directly (for example,p { color: … }), and a direct rule always beats an inherited value. - Copying a
<style>between pages "just this once": as soon as there are two copies, they drift apart. - Assuming HTML emails follow the rules of the web: The Blue Cup's newsletter, if it's ever designed, will need inline styles and specialised tools.
- Tip: when two rules compete, ask yourself in this order: is there an
!important? Is there an inlinestyle? Which selector is more specific? Which comes later? Almost every mystery is solved there.
Exercises
Exercise 1. For each case, say which way of applying CSS you would use and why:
- The monthly newsletter that The Blue Cup will email to its subscribers.
- The background colour of every card on the site.
- Trying out whether the menu looks better in another blue, just to show the owner on your computer.
- A progress bar that a script updates while a file is uploading.
Exercise 2. Given this HTML and CSS, say what colour each paragraph is and why:
<section id="opening-hours">
<p>We're open every day.</p>
<p class="note">Bank holidays: please ask.</p>
<p class="note" id="august-note">Closed from 1 to 15 August.</p>
<p class="note" style="color: purple;">Bread-making workshop: first Saturday of every month.</p>
</section>#august-note { color: red; }
.note { color: gray; }
p { color: black; }
#opening-hours { color: navy; }
.note { color: green; }Exercise 3. A colleague can't get the text of the bookings card to show in white. They have this:
It works, but explain why it's a poor solution and what the right one would be.
Solutions
Solution 1.
- Inline: email programs often discard
<style>and don't load external stylesheets. It's best designed with a tool that converts the rules intostyleattributes automatically. - External: it's a style common to the whole site; a
.cardrule instyles.css. - DevTools' Styles pane (or, at most, a temporary
<style>): it's a test that mustn't affect the site. If the owner likes it, it goes into the stylesheet. - Inline, written by JavaScript (
element.style.width = "40%"): the value changes continuously. The bar's fixed look (colours, borders) would still go in the stylesheet.
Solution 2.
- "We're open every day." → black. The
prule affects it directly. The#opening-hoursrule would only provide an inherited colour, and a direct rule, however weak, beats inheritance. - "Bank holidays: please ask." → green. The two
.noterules have the same specificity and the last one wins. Both beatp. - "Closed from 1 to 15 August." → red.
#august-noteis an ID selector, more specific than.note, even though it appears earlier. - "Bread-making workshop…" → purple. The
styleattribute beats any selector.
Solution 3. The inline style is the underlying problem, and the !important covers it up instead of solving it. If tomorrow someone wants a different colour for the cards, they'll have to fight an !important and discover that there's also a style in the HTML. The right solution is to remove the style attribute from the link and keep a normal rule:
Without the inline style, .card is enough on its own to beat the general rule for links (if there were one of type a), because a class is more specific than a tag.
Conclusion
You now know the three ways of applying CSS: the style attribute, which affects a single element and beats almost everything; the <style> element, which affects one page; and the external stylesheet, which serves the whole site and takes advantage of the cache. You know that the first two have their place in specific cases (HTML emails, prototypes, critical CSS, values calculated by JavaScript) and that on a normal website everything goes into the external stylesheet. You've understood the cascade: importance, origin, inline styles, specificity and order decide which declaration wins, and inheritance passes certain values down to descendants. You also know why !important is a patch best avoided. The Blue Cup has no scattered styles and its styles.css is organised into nine sections, ready to grow. But in this lesson you've used specificity intuitively ("a class outweighs a tag"). In the next one, Basic CSS Selectors, you'll meet all the selectors you need to target any element on the site precisely, learn to calculate their exact specificity and style the menu, the links and the focus states.
HTML Course
Module 1: Introduction to HTML
- What Is HTML?
- Setting Up Your Work Environment
- Basic Structure of an HTML Document
- Tags, Elements and Attributes
- Creating Your First HTML Page
- File Organisation and Paths
Module 2: Text Formatting in HTML
- Headings and Paragraphs
- Text Formatting Tags
- Lists: Ordered, Unordered and Description Lists
- Block Quotes and Preformatted Text
- Block and Inline Elements: div and span
Module 3: Links and Media in HTML
- Creating Hyperlinks
- Special Links: Anchors, Email, Phone and Downloads
- Adding Images
- Embedding Videos
- Using the Audio Element
Module 4: Tables in HTML
- Basic Table Structure
- Table Head, Body and Foot
- Merging Cells: colspan and rowspan
- Accessible Tables: caption, scope and headers
- Styling Tables
Module 5: Forms in HTML
- Creating a Basic Form
- Form Elements: input, textarea and select
- HTML5 Input Types
- Labels and Grouping: label, fieldset, legend and datalist
- Form Attributes and Validation
- Submitting Forms
Module 6: HTML5 Semantic Elements
- Introduction to Semantic HTML
- header, nav and footer
- article, section and aside
- main and figure
- Other Semantic Elements: time, address, details and dialog
Module 7: Advanced HTML Techniques
- HTML Entities
- Using iframes
- Data Attributes
- Metadata: meta, SEO and Open Graph
- Microdata and Structured Data
- Graphics in HTML: SVG and canvas
Module 8: Integrating HTML and CSS
- Linking CSS to HTML
- Inline, Internal and External CSS
- Basic CSS Selectors
- The Box Model
- Styling HTML Elements
- Introduction to Layout with Flexbox and Grid
Module 9: Responsive Web Design
Module 10: Best Practices and Accessibility
- HTML Best Practices
- Validating HTML Code
- Web Accessibility Basics
- Using ARIA Roles and Attributes
- Accessibility Testing
- Performance and Resource Loading
