EthicsComputerCourses
Join training +91 90532 10052

How CSS Works in Browsers

CSS · Lesson 4 of 240 Beginner 11 min read Updated

By the end of this lesson you will be able to explain, step by step, what a browser does with your CSS file. You will look inside the browser's copy of your style rules, read the final values it works out for an element, and see which changes make the browser redo a lot of work and which are cheap.

In Introduction to CSS you saw a five-line summary of this process. This lesson slows it down. It stays at beginner depth; the HTML course goes much deeper in Browser Rendering Fundamentals, Browser Rendering Pipeline and Critical Rendering Path.

The big picture

Think of a wedding hall in Jaipur being decorated. The guest list says who is coming (the HTML). The decorator's notes say "red cloth on every table, gold lights near the stage" (the CSS). Someone matches the notes to each table, someone measures where every table stands, the painters and florists do their work, and finally everything is put together for the guests to see.

A browser follows the same order. These are the main stages:

Text
HTML  ->  DOM ----\
                   >--> Style --> Layout --> Paint --> Composite --> screen
CSS   ->  CSSOM --/
StageQuestion it answers
Parse HTMLWhat elements are on the page?
Parse CSSWhat style rules exist?
StyleWhich rules apply to each element, and what is the final value of each property?
LayoutHow big is each box, and where does it go?
PaintWhat does each box look like: colours, text, borders?
CompositeHow do the painted layers stack together into one picture?

Step 1: parsing HTML into the DOM

Parsing means reading text and turning it into a structure the program can work with. The browser reads your HTML from top to bottom and builds the DOM (Document Object Model): a tree where every element is a node, with parents and children. You met it in DOM Structure & HTML Parsing.

While parsing, the browser finds <link rel="stylesheet"> elements and <style> elements. It starts downloading external CSS files at once, while it carries on reading the HTML.

Step 2: parsing CSS into the CSSOM

Each style sheet is parsed into the CSSOM (CSS Object Model). It is the browser's organised list of your rules, selectors and declarations. JavaScript can read it through document.styleSheets.

The CSS parser has one important habit: when it meets something it does not understand, it drops just that piece and keeps going. You saw this from the outside in CSS Syntax & Rules. The example below shows it from the inside. It prints the rules exactly as the browser stored them.

HTMLOpen in editor
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Inside the CSSOM</title>
  <style>
    .notice {
      color: #1a4d8f;
      colr: red;
      font-size: 1.5 rem;
      padding: 12px;
    }
    .notice strong { text-transform: uppercase; }
  </style>
</head>
<body>
  <p class="notice"><strong>Holiday:</strong> school closed on Friday for Holi.</p>
  <pre id="out"></pre>
  <script>
    const lines = [];
    for (const rule of document.styleSheets[0].cssRules) {
      lines.push(rule.cssText);
    }
    document.querySelector("#out").textContent = lines.join("\n");
  </script>
</body>
</html>

In Chrome the box under the notice shows:

Output
.notice { color: rgb(26, 77, 143); padding: 12px; }
.notice strong { text-transform: uppercase; }

The misspelt colr and the broken 1.5 rem are not in the CSSOM at all. As far as the browser is concerned, you never wrote them. Notice also that the browser rewrote #1a4d8f in its own format, rgb(26, 77, 143). The colour is the same; only the way it is written changed.

Step 3: style calculation

Now the browser has two trees: the DOM (what is on the page) and the CSSOM (the rules). In the style stage it walks through every element and does three jobs:

  1. Matching. It finds every rule whose selector matches the element.
  2. The cascade. When two rules set the same property, it picks a winner. The browser's own default styles lose to yours, and more specific selectors beat less specific ones. You will study this in CSS Specificity.
  3. Inheritance and defaults. If no rule sets a property, the element either inherits it from its parent (as color does) or uses the property's starting value.

The result is the computed style of the element: one value for every CSS property. Relative values are turned into fixed ones where possible, so 2em becomes a number of pixels. You can read these values with getComputedStyle().

HTMLOpen in editor
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Computed styles</title>
  <style>
    body { font-family: system-ui, sans-serif; color: darkgreen; }
    .score { font-size: 2em; padding: 0.5em; background: gold; }
  </style>
</head>
<body>
  <p class="score">India 287/6 <span>(50 overs)</span></p>
  <pre id="out"></pre>
  <script>
    const score = getComputedStyle(document.querySelector(".score"));
    const overs = getComputedStyle(document.querySelector(".score span"));
    document.querySelector("#out").textContent = [
      "font-size: " + score.fontSize,
      "padding-top: " + score.paddingTop,
      "color: " + score.color,
      "background-color: " + score.backgroundColor,
      "display: " + score.display,
      "span color: " + overs.color,
      "span font-size: " + overs.fontSize
    ].join("\n");
  </script>
</body>
</html>
Output
font-size: 32px
padding-top: 16px
color: rgb(0, 100, 0)
background-color: rgb(255, 215, 0)
display: block
span color: rgb(0, 100, 0)
span font-size: 32px

Read each line slowly:

  • 2em became 32px, because the default text size is 16px (if you changed your browser's font size, you will see a different number).
  • padding: 0.5em became 16px, because em here uses the paragraph's own 32px size.
  • The paragraph never set color, but it got dark green by inheritance from body. The span inherited it too.
  • display: block came from the browser's default style sheet, not from your CSS.

Step 4: layout

The computed style says what each box wants, but not where it goes. In the layout stage the browser calculates the exact width, height and position of every box. It starts from the size of the window and works down the tree. A paragraph's width depends on its parent's width, and its height depends on how many lines its text needs.

This is why the same page looks different on a phone and a laptop: the window width changes, so layout gives different answers. Elements with display: none are skipped completely here, because they produce no box.

Firefox calls this stage reflow. You will hear both words.

Step 5 and 6: paint and composite

In the paint stage the browser decides how to draw each box: background first, then borders, then text, in the right stacking order. Modern browsers record these as a list of drawing instructions and turn them into pixels a little later.

Some parts of a page are drawn on separate layers, like the transparent sheets an old overhead projector used in classrooms. In the composite stage the browser stacks the layers in order to make the final picture, often with help from the graphics chip (GPU). Moving a whole layer is cheap, because nothing needs to be measured or drawn again.

What happens when CSS changes

A page is not drawn just once. Every time a style changes (on hover, on a click, from JavaScript), the browser runs the stages again, starting from the earliest one the change affects.

You changeStages the browser runs again
width, padding, font-size, displayStyle, layout, paint, composite
color, background-color, box-shadowStyle, paint, composite
transform, opacity (usually)Style, composite

Try the three buttons below and watch the other boxes.

HTMLOpen in editor
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Layout, paint and composite</title>
  <style>
    body { font-family: system-ui, sans-serif; padding: 1rem; }
    .row { display: flex; gap: 8px; margin-bottom: 1rem; }
    .box { width: 90px; padding: 12px; background: #fde2b8; border: 2px solid #c06014; }
    .wide { width: 200px; }
    .green { background: #c8ecc9; }
    .moved { transform: translateX(40px); }
    button { font: inherit; margin-right: 6px; }
  </style>
</head>
<body>
  <div class="row">
    <div class="box" id="first">Samosa</div>
    <div class="box">Kachori</div>
    <div class="box">Jalebi</div>
  </div>
  <button data-change="wide">Change width (layout)</button>
  <button data-change="green">Change colour (paint)</button>
  <button data-change="moved">Transform (composite)</button>
  <script>
    const first = document.querySelector("#first");
    for (const button of document.querySelectorAll("button")) {
      button.addEventListener("click", () => first.classList.toggle(button.dataset.change));
    }
  </script>
</body>
</html>
  • Change width makes the first box wider, so Kachori and Jalebi slide right. The browser had to redo layout for the whole row.
  • Change colour only repaints the first box. Nothing else moves.
  • Transform slides the first box over its neighbour, but the neighbours stay where they were. A transform moves the painted picture of the box, not its place in the layout.

This is the reason animation lessons later in the course prefer transform and opacity.

CSS blocks the first paint

A browser will not show the page until it has the style sheets in <head>. If it painted early, you would first see plain black text and then a sudden jump when the styles arrive. That ugly jump is called a flash of unstyled content (FOUC). So CSS is render-blocking: a slow, large style sheet makes the whole page appear late.

This gives you two early habits. Keep your CSS files reasonably small, and put <link rel="stylesheet"> in the <head>, not at the end of the body. Level 7 covers the professional techniques in Critical CSS.

Common mistakes

  • Expecting the browser to report CSS errors. It silently drops what it cannot parse. Check the Styles panel in DevTools, where dropped declarations appear crossed out with a warning icon.
  • Putting the style sheet link at the bottom of the body. The page may show unstyled for a moment, then jump.
  • Animating width, top or margin for movement. Each frame forces layout again. Use transform instead.
  • Thinking the DOM and the HTML file are the same thing. The DOM is the browser's tree built from your file, and JavaScript or the parser may change it.

Interview questions

1. What is the CSSOM, and how is it different from the DOM?

The DOM is a tree of the page's elements built from the HTML. The CSSOM is the browser's model of the style sheets: the rules, selectors and declarations it parsed from the CSS. The browser combines the two in the style stage to work out each element's computed style.

2. What does the browser do with a CSS declaration it cannot understand?

It ignores that declaration and continues with the next one. If the selector itself is invalid, the whole rule is dropped. The ignored parts never reach the CSSOM, which is why new CSS features do not break older browsers.

3. What is the difference between layout and paint?

Layout calculates the size and position of every box. Paint decides what each box looks like, such as its colours, text and borders. Changing width needs layout and paint again, while changing only background-color needs paint but not layout.

4. Why is CSS called render-blocking?

The browser waits for the style sheets in <head> before it paints the page, so users do not see a flash of unstyled content. A large or slow style sheet therefore delays the first view of the page.

5. Why are transform and opacity good for animation?

In modern browsers they can usually be handled in the composite stage alone, without layout or paint. The browser just moves or fades an already painted layer, which is much cheaper and keeps the animation smooth.

Key points

  • The browser parses HTML into the DOM and CSS into the CSSOM.
  • Invalid declarations are dropped during parsing and never reach the CSSOM.
  • The style stage matches rules, applies the cascade and inheritance, and produces the computed style.
  • Layout works out box sizes and positions; paint and composite produce the pixels.
  • A change to geometry (such as width) costs more than a change to colour, and transform costs least.
  • Style sheets in <head> block the first paint, so keep them small.

Exercise

Make a small page for a cricket scorecard in Pune. Add a <style> block that sets font-size: 1.25em and color: navy on a .team class, and include one deliberately invalid declaration. Add a <script> that prints two things: every rule's cssText from document.styleSheets[0], and the computed font-size and color of the .team element. Before you run it, write down what you expect each value to be.

Show solution
HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Scorecard check</title>
  <style>
    .team { font-size: 1.25em; color: navy; widht: 300px; }
  </style>
</head>
<body>
  <p class="team">Pune Panthers 164/8</p>
  <pre id="out"></pre>
  <script>
    const rules = [...document.styleSheets[0].cssRules].map(r => r.cssText);
    const team = getComputedStyle(document.querySelector(".team"));
    document.querySelector("#out").textContent =
      rules.join("\n") + "\nfont-size: " + team.fontSize + "\ncolor: " + team.color;
  </script>
</body>
</html>

The rule prints without widht, because the misspelt property was dropped while parsing. With a 16px default font, the computed font-size is 20px (16 x 1.25) and navy is shown as rgb(0, 0, 128).

Quick Quiz

1. What does the browser build from your CSS files?

2. A rule contains colr: red;. What happens to that declaration?

3. Which change makes the browser redo layout?

4. Why should <link rel="stylesheet"> go in the <head>?

Learn CSS with a mentor

Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call