Your country

Tools that support it use your country for local currency, number formats, units and paper size. Your choice is saved only in this browser.

Type a name or a two-letter code. Use the up and down arrow keys to move through the countries, Enter to choose one and Escape to close.

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.

  • Beginner
  • 25 minutes
  • Examples run with Node.js 24.21.0
  • By MySmartCoPilot
Free core, Pro depth: 10 of 25 minutes free
Free: Shared styles belong in linked files · Equal declarations follow source order · Browser defaults are a starting style layer. With a pass: 2 in-depth parts and 3 interview answers, about 15 minutes.

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.

The three ways in one page HTML · three-ways.html
<!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

link, style or style attribute?
Criterion <link><style>style=
Lives in A .css fileThe pageOne element
Styles Every page linking itOne pageOne element
Cached YesNoNo
Can use :hover YesYesNo
Priority UsualUsualHigher
Under style-src 'self' AllowedBlockedBlocked
When to choose Almost all CSSOne page, critical CSSValues 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

  1. Question 1 of 2 Forty pages share the same presentation. Which placement avoids repeating that CSS in every page?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: A linked stylesheet shared by the pages

    A separate stylesheet can be maintained once and reused through the browser cache on subsequent pages.

  2. Question 2 of 2 A page uses style-src 'self' without an inline-style allowance. Which source remains usable?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: A linked stylesheet from that origin

    The policy allows the page's own external stylesheet source, while the unapproved inline block and attributes are blocked.

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.

Three sources of CSS, weakest first: browser defaults, then your stylesheets, then style attributes on single elements.Browser defaultsthe user-agent stylesheet:margins, heading sizes, link coloursYour stylesheets<link>, <style> and @import:selectors decide what matches,then specificity and order decide tiesstyle attributesdeclarations on one element,no selectors, no media queriesoverridden byoverridden by

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.

  1. Browser defaults: the user-agent stylesheet, which sets things like margins, heading sizes and link colours before any of your CSS loads.
  2. 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.
  3. 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:

Interactive · stage by stage Equal declarations follow their source order Keep the same .button selector and normal importance in both linked files, then change only which link comes last.
Equal declarations follow their source order, step 3 of 3. Showing Read library.css, Read site.css, Resolve the tie. In focus: Resolve the tie.Read library.cssRead site.cssResolve the tie

The drawing shows the whole scene; its 3 steps are listed below.

Every step as text
  1. Identify the equality. Both declarations use .button and the same normal importance. Their selectors do not differ in specificity in this case.
  2. 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.
  3. 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

  1. Question 1 of 2 Two identical selectors set the same normal property in linked sheets. What decides the tie described here?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: Their source order in the link elements

    The cascade treats linked sheets in the order they appear; download arrival order does not decide the tie.

  2. Question 2 of 2 Three CSS files are discovered one after another through imports. Each request takes 200 ms. When does the third arrive in this simplified case?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: At 600 ms

    The files are discovered sequentially: 200 ms, then 400 ms, then 600 ms. This uses the same dependency rule as the complete retained waterfall program.

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

  1. Question 1 of 2 Why does a page remain readable before an author stylesheet is applied?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: The browser supplies default styles

    The user-agent stylesheet already gives paragraphs, headings, lists and links a basic presentation.

  2. Question 2 of 2 Body text uses one font, while buttons use the browser's separate control font. Which base rule aligns their fonts?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: font: inherit on the controls

    The rule makes the controls inherit the surrounding font properties while retaining their useful control behaviour.

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.

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.

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.

  1. Question 1 of 11 Your site has 40 pages that share one look. Where should most of its CSS go?

    Choose one answer.

    Show the answer: Question 1 of 11

    Answer: In one or a few .css files, linked from every page with <link rel="stylesheet">

    A linked stylesheet is written once, used by every page and cached by the browser after the first one, so the next pages need no new request for it. A <style> element repeats the CSS in every page, style attributes repeat it on every element and cannot use selectors or media queries, and an @import adds a request that can start only after the importing CSS has been read.

  2. Question 2 of 11 What colour is the paragraph's text?

    Read the code, then choose one answer.

    <style>
      #intro.lead { color: navy; }
    </style>
    <p id="intro" class="lead" style="color: darkgreen">Welcome</p>
    Show the answer: Question 2 of 11

    Answer: darkgreen

    These declarations share the author origin and styling context. At the same importance, the attached style attribute beats the selector rule regardless of specificity. An !important declaration or a running animation can override a normal attribute in other cases; neither is present here.

  3. Question 3 of 11 A page links app.css, which imports layout.css, which imports colours.css. Every request takes 200 ms and starts the moment the browser knows about the file. After how many milliseconds have all three stylesheets arrived?

    Type a number.

    Show the answer: Question 3 of 11

    Answer: 600 ms

    The browser learns about each imported file only when the file that imports it has arrived: app.css arrives at 200 ms, layout.css at 400 ms and colours.css at 600 ms. Three links in the HTML would all have arrived at about 200 ms.

  4. Question 4 of 11 A page links library.css and then site.css. Both contain a rule with the selector .button, and they set different background colours. Which background does a button get?
    Show the answer: Question 4 of 11

    Answer: The one from site.css, because it comes later and the selectors are equally specific

    With the same selector, the declarations tie on specificity, so the order of appearance decides, and linked stylesheets count in the order of their <link> elements. Download order does not matter. A more specific selector in library.css would still win, though.

  5. Question 5 of 11 A page is served with Content-Security-Policy: style-src 'self'. Which of these styles still apply?

    Choose every answer that is right.

    Show the answer: Question 5 of 11

    Answer:

    • A stylesheet on the same site, linked with <link rel="stylesheet">

    'self' permits the same-origin linked stylesheet, not the inline block or attribute in this case. An 'unsafe-inline' allowance can permit inline styles. For a style element, a nonce or matching content hash is an alternative. A nonce cannot authorize a style attribute, and an attribute hash also needs 'unsafe-hashes'. External stylesheets from other origins require their own permitted sources.

  6. Question 6 of 11 Forty pages share the same presentation. Which placement avoids repeating that CSS in every page?

    Choose one answer.

    Show the answer: Question 6 of 11

    Answer: A linked stylesheet shared by the pages

    A separate stylesheet can be maintained once and reused through the browser cache on subsequent pages.

  7. Question 7 of 11 A page uses style-src 'self' without an inline-style allowance. Which source remains usable?

    Choose one answer.

    Show the answer: Question 7 of 11

    Answer: A linked stylesheet from that origin

    The policy allows the page's own external stylesheet source, while the unapproved inline block and attributes are blocked.

  8. Question 8 of 11 Two identical selectors set the same normal property in linked sheets. What decides the tie described here?

    Choose one answer.

    Show the answer: Question 8 of 11

    Answer: Their source order in the link elements

    The cascade treats linked sheets in the order they appear; download arrival order does not decide the tie.

  9. Question 9 of 11 Three CSS files are discovered one after another through imports. Each request takes 200 ms. When does the third arrive in this simplified case?

    Choose one answer.

    Show the answer: Question 9 of 11

    Answer: At 600 ms

    The files are discovered sequentially: 200 ms, then 400 ms, then 600 ms. This uses the same dependency rule as the complete retained waterfall program.

  10. Question 10 of 11 Why does a page remain readable before an author stylesheet is applied?

    Choose one answer.

    Show the answer: Question 10 of 11

    Answer: The browser supplies default styles

    The user-agent stylesheet already gives paragraphs, headings, lists and links a basic presentation.

  11. Question 11 of 11 Body text uses one font, while buttons use the browser's separate control font. Which base rule aligns their fonts?

    Choose one answer.

    Show the answer: Question 11 of 11

    Answer: font: inherit on the controls

    The rule makes the controls inherit the surrounding font properties while retaining their useful control behaviour.

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.

  1. 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.

    Model answer, Pro. Model answers open with any pass; prices are in the notice on this page. First step and follow-ups

  2. 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'?

    Model answer, Pro. First step and follow-ups

  3. 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.

    Model answer, Pro. First step and follow-ups

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 style attribute holds declarations only, beats author rules of the same importance here, and is blocked by a strict Content Security Policy.
  • Each level of @import adds 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

Related tools

Report a problem with this lesson

Quick answers and tool search

Type to search tools or to get a quick answer, for example 18% of 2500. Use the up and down arrow keys to move through the results, Enter to choose, and Escape to close.