CSS Module 1 – How CSS works
Adding CSS to HTML and browser default styles
Add CSS with a link element, a style element or a style attribute, see what browsers style before your CSS loads, and write a small base stylesheet.
What you will learn
- Add CSS with a link element, a style element and the style attribute, and choose the right one for a job
- Explain what the browser's default (user-agent) styles do before any CSS is written
- Predict which of two linked stylesheets wins when their selectors tie
- Write a small modern base stylesheet instead of copying a large reset
Before you start
What you’ll learn · Before you start
What you will learn
- Add CSS with a link element, a style element and the style attribute, and choose the right one for a job
- Explain what the browser's default (user-agent) styles do before any CSS is written
- Predict which of two linked stylesheets wins when their selectors tie
- Write a small modern base stylesheet instead of copying a large reset
Before you start
On this page
There are three ways to add CSS to an HTML page. A <link rel="stylesheet"> element in the <head> loads a separate
.css file, and it is the right choice for almost all CSS: one file styles every page that links it, and the browser
keeps a copy for the next page. A <style> element holds CSS inside the page itself, which suits styles that only that
page needs. A An HTML attribute containing CSS declarations attached to a single element, without a selector rule. puts declarations on a single element. It beats author stylesheet rules of the same importance here, but it
cannot use selectors, media queries or states such as :hover. And before any of your CSS arrives, the browser has
already styled the page with its own defaults: a margin around the body, large bold headings, blue underlined links.
This lesson shows the three ways and when each fits, measures the defaults in Chromium, Firefox and WebKit, and ends with a short base stylesheet that keeps the useful defaults and changes the rest.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Order status</title>
<!-- 1. A link element: an external stylesheet, shared by every page that links it -->
<link rel="stylesheet" href="/css/site.css">
<!-- 2. A style element: CSS for this page only -->
<style>
.status {
font-weight: 600;
}
</style>
</head>
<body>
<!-- 3. A style attribute: declarations for this one element -->
<p class="status" style="color: #0b6e4f">Your parcel is on its way.</p>
</body>
</html> Shared styles belong in linked files
| Criterion | <link> | <style> | style= |
|---|---|---|---|
| Lives in | A .css file | The page | One element |
| Styles | Every page linking it | One page | One element |
| Cached | Yes | No | No |
| Can use :hover | Yes | Yes | No |
| Priority | Usual | Usual | Higher |
| Under style-src 'self' | Allowed | Blocked | Blocked |
| When to choose | Almost all CSS | One page, critical CSS | Values set by scripts |
The rest of this lesson takes the three in turn, then looks at what happens when two stylesheets disagree.
Adding CSS to HTML with a linked sheet separates document structure from presentation shared by its pages. Adding CSS to HTML with a style element instead puts it inside one document, so another page needing those rules repeats its text. A style attribute attaches values to one element and cannot describe hover selectors or media conditions. These are different tools even when each can make one piece of text green.
A strict A browser policy that restricts which sources and kinds of content a document may use. is another reason to prefer a linked file. With style-src ‘self’ and no inline allowance, the same-origin linked sheet can apply while the style block and attribute cannot. That policy question is separate from cascade priority: an inline declaration can be strong in the cascade but unusable under the page’s policy.
Checkpoint
Check: Choosing a place for CSS
Equal declarations follow source order
When two declarations for the same property tie on everything else the cascade looks at, the one that comes later
wins. Separately linked stylesheets count as if they were joined end to end in the order of their <link> elements,
and an imported stylesheet counts as if its rules were pasted where the @import stands. So if a library’s
stylesheet and yours both set .button { background: … }, link yours after the library’s and yours wins.
That is order between equals. A more specific selector earlier in the page still beats a less specific one later, and the cascade module explains how The selector-based comparison used to resolve a cascade tie after the earlier priority conditions. is counted.
Where an element's styles come from
Text description of the diagram
The diagram stacks the three places an element's normal declarations come from, from the weakest at the top to the strongest at the bottom.
- Browser defaults: the user-agent stylesheet, which sets things like margins, heading sizes and link colours before any of your CSS loads.
- Your stylesheets, from link elements, style elements and @import: selectors decide which elements a rule matches, and when two rules set the same property, specificity and then the order of the rules decide which one wins. They override the browser defaults.
- style attributes: declarations attached to one element, with no selectors and no media queries. They override declarations from your stylesheets.
Declarations marked !important change this order; the cascade module of this track covers them.
A discovery dependency can also affect time without changing this source order. In a simplified three-file chain with 200 ms per request, the third file is known only after two earlier files arrive, so it arrives at 600 ms. Three addresses already known from the HTML can instead be requested together.
Compare library.css and site.css with the same .button selector; the download order does not change this sequence:
The drawing shows the whole scene; its 3 steps are listed below.
Every step as text
- Identify the equality. Both declarations use .button and the same normal importance. Their selectors do not differ in specificity in this case.
- Read the later source. The site.css link follows the library.css link. Their place in the source is fixed even if the responses arrive in another order.
- Choose the later value. The later declaration wins the remaining tie. A more specific earlier selector would be a different case, which the original full text also retains.
Checkpoint
Check: Order between equal rules
Browser defaults are a starting style layer
Browser default styles come from a user-agent stylesheet: The browser's own CSS rules that give an HTML document its default presentation. that gives headings, paragraphs, lists and links a usable starting presentation before author CSS. Browser default styles are not the site’s design: normal author rules can replace them. Keeping useful defaults is different from assuming that every engine chooses identical fonts for form controls.
For example, a button can have the browser’s control font while the surrounding page uses another font. A base rule with font: inherit on buttons, inputs, selects and text areas makes those controls use the surrounding font properties. It does not turn a background colour into a font setting, remove the controls’ behaviour, or reset every heading and list.
| Style layer | What the core case uses |
|---|---|
| Browser defaults | A basic presentation before author rules. |
| Author base | Selected changes such as inherited control fonts. |
| Component rules | The page-specific presentation built on that base. |
Checkpoint
Check: Browser defaults and a base
Request dependencies, inline priority and policy Pro: opens with a Pro, Premium or Ultimate pass
One shared stylesheet can still create a long wait or an unexpected winner. The complete examples below distinguish resource discovery, cascade priority and the policy that permits a style to apply.
In this part:
- Request dependencies explain the blank screen
- Inline CSS has distinct priority and policy rules
2 diagrams · 3 runnable examples (HTML, JavaScript, main.css, theme.css, type.css) · about 8 minutes
Opening this part with your pass…
This part opens with any MySmartCoPilot pass.
- Pro pass · 1 week₹79$2.99
- 30 days₹179$5.99
- 1 year₹1,699$45
One payment; nothing renews unless you choose to. The price shown is the total you pay: no fees or charges are added at checkout.
Passes can’t be bought right now, so this part can’t be opened at the moment. The free part above stands on its own. If you have a pass, enter your licence key.
It also opens every other in-depth part in Learn and every Pro tool. Sales are final, except where the law gives you a right to withdraw, for example in the EU and the UK (refund policy).
Browser measurements and a selective style base Pro: opens with a Pro, Premium or Ultimate pass
The measurements separate shared defaults from engine differences. The base stylesheet and promo-card refactoring then change only the presentation that needs changing.
In this part:
- Measured defaults explain cross-browser differences
- A small base and a class-based card keep control
2 diagrams · 3 runnable examples (CSS, HTML) · about 7 minutes
Opening this part with your pass…
This part opens with any MySmartCoPilot pass.
- Pro pass · 1 week₹79$2.99
- 30 days₹179$5.99
- 1 year₹1,699$45
One payment; nothing renews unless you choose to. The price shown is the total you pay: no fees or charges are added at checkout.
Passes can’t be bought right now, so this part can’t be opened at the moment. The free part above stands on its own. If you have a pass, enter your licence key.
It also opens every other in-depth part in Learn and every Pro tool. Sales are final, except where the law gives you a right to withdraw, for example in the EU and the UK (refund policy).
Practise: choose a placement and predict its result
Choose a placement and predict its resulting styles.
Practice that adapts to you
Practise this lesson
11 questions about 7 ideas of this lesson. Each answer is explained at once, and what you get right is kept in this browser.
Interview questions
What is the difference between linking a stylesheet with <link> and loading it with @import?
Both load an external stylesheet, but the browser finds them at different times. A <link rel="stylesheet"> sits in
the HTML, so the browser sees it while parsing the <head> and can request every linked stylesheet at once. An
@import sits inside a stylesheet, so the imported file can be requested only after the file containing it has
arrived and been read; a chain of imports therefore costs one full round trip per level, while the page waits. In a
test with 300 ms per request, three chained stylesheets finished loading after 0.9 to 1.1 seconds and three links
after 0.3 to 0.5. For the cascade, the two are equivalent: an imported stylesheet counts as if its rules were written
where the @import stands. Use <link>, or combine files when the site is built.
-
Fresher to mid
A page links one stylesheet, app.css, which imports vendor.css, which imports fonts.css. On a phone, first visits show a blank screen for well over a second. Explain why, estimate the wait for a 250 ms round trip, and fix it without changing a single CSS rule.
-
Mid to senior
Your team adds a Content-Security-Policy with style-src 'self' to a dashboard. After the release, several components lose colours and a chart library's layout collapses. What broke, how do you find every affected place, and how do you fix it without adding 'unsafe-inline'?
-
Fresher to mid
A shared form inherits the site's font in one browser, but its buttons keep a different font in another. Headings and paragraph gaps differ too. Explain the source of these differences and choose a small shared stylesheet that makes the intended choices without discarding usable control states.
Key takeaways
- Link stylesheets with
<link rel="stylesheet">in the<head>: it is cached, works on every page and blocks rendering only until it arrives. - A
<style>element is for one page’s styles or a small critical block; it arrives with the HTML and is not cached separately. - A
styleattribute holds declarations only, beats author rules of the same importance here, and is blocked by a strict Content Security Policy. - Each level of
@importadds a full request before the page can render; link the files instead. - Between equally specific rules, the later one wins, in the order of the
<link>elements, with imports counted in place.
Terms in this lesson
- render-blocking
- A stylesheet dependency that must be ready before the browser may show the page's initial rendering.
- user-agent stylesheet
- The browser's own CSS rules that give an HTML document its default presentation.
References
- HTML Standard: the link element, link type "stylesheet" (WHATWG)
- HTML Standard: the style element (WHATWG)
- HTML Standard: render-blocking mechanism (WHATWG)
- HTML Standard: Rendering (the expected default styles) (WHATWG)
- CSS Cascading and Inheritance Level 5 (W3C CSS Working Group)
- CSS Style Attributes (W3C CSS Working Group)
- Content Security Policy Level 3 (W3C Web Application Security Working Group)
Related tools
Report a problem with this lesson
Kept only in this browser. Your Learn progress