Skip to content

Lesson 45 of 52Performance and tooling

Browser DevTools for HTML, CSS and Performance

Use DevTools like a senior frontend engineer: trace the winning CSS rule, read a network waterfall, find long tasks and forced reflows, and emulate users.

20 min read0/5 questions

A ticket lands on Monday morning: "On the product page the Buy button sits too low on phones, the hero image takes ages to appear, and the filter panel feels sticky on cheap Android devices." Three symptoms, three different tools. Juniors guess, change some CSS and reload. Seniors ask the browser what it actually did: which rule won, which request waited, which task blocked the main thread. This lesson covers the panels that answer those questions for HTML, CSS and performance, in Chrome first and then the places where Firefox and Safari do it better. JavaScript breakpoints live in the Errors and Debugging lesson of the JavaScript & TypeScript course, so they are not repeated here.

Elements: reading the cascade the way the browser does

CSS Basics showed you how to inspect an element and spot a crossed-out declaration. At work you need to read the Styles pane more precisely, because it shows three different kinds of "this did not apply", and each has a different fix.

  • Struck through, normal colour. The declaration is valid but lost the cascade. Something with a later layer, higher specificity or later source order won. Look further up the pane for the winner.
  • Struck through with a warning triangle. The browser could not parse it: a typo in the property name, an invalid value, or a feature this browser does not support. The cascade never even saw it.
  • Dimmed, with an info icon. The declaration is valid and won, but it does nothing in this context. justify-content on an element that is not a flex or grid container, width on an inline span, z-index on a box that does not create a stacking context. Hover the icon and Chrome tells you why and what to add. Firefox pioneered this "inactive CSS" hint and its wording is often clearer.

Rules in the Styles pane are listed in cascade order, so the top rule is the strongest. Each rule header shows its source file and line, and with source maps it points at your original Sass, CSS Modules or Tailwind input instead of the bundled file. If the rule sits in a cascade layer, the header shows the layer name, and clicking it shows the full layer order for the page. Hover any selector to see its specificity, such as (0,1,1).

The Computed pane answers a different question. Styles tells you why; Computed tells you what. Find a property in Computed, expand its arrow, and you see every declaration that tried to set it, with the winner on top and a link to its source. When a value comes from inheritance (a color set on body, say), Computed is the only quick way to see that the element itself has no rule at all.

Forcing states and editing in place

Hover and focus styles vanish the moment you move the mouse to DevTools. The :hov button in the Styles toolbar forces :hover, :active, :focus, :focus-visible, :focus-within, :visited and :target on the selected element. The .cls button toggles classes, which is the fastest way to try a variant without editing HTML.

For focus specifically, open the Rendering drawer and tick Emulate a focused page. Without it, clicking into DevTools takes focus away from the page and your :focus-visible ring disappears.

The box model diagram at the bottom of the Styles pane is editable: double-click a margin or padding number and type. Grid, flex, container and scroll containers get a small badge next to them in the DOM tree. Click a grid badge to draw line numbers, track sizes and area names over the page, and use the Layout pane to keep several overlays on at once.

Every edit you make is lost on reload. The Changes tab (open it from the command menu with Cmd+Shift+P or Ctrl+Shift+P and type "Changes") lists every CSS edit as a diff that you can copy back into your source. When something keeps changing an element and you do not know what, right-click the node and choose Break on > attribute modifications or subtree modifications. The next time any script touches it, the debugger pauses on the exact line.

Try it now. Right-click inside the preview below and choose Inspect. The preview is a normal page in an iframe, so DevTools works on it.

HTML & CSS
<style> .toolbar { justify-content: flex-end; gap: 12px; padding: 12px; border: 1px solid #ccc; } .badge { width: 120px; background: #fde68a; } #checkout button { background: #6b7280; color: white; } .btn-primary { background: #2563eb; padding: 8px 16px; border: 0; } .btn-primary { colr: white; }</style><div id="checkout"> <div class="toolbar"> <span class="badge">Free delivery</span> <button class="btn-primary">Buy now</button> </div></div>

Preview

Your job: the button should be blue, the toolbar should push its items to the right, and the badge should be 120px wide. Inspect each element and find all three reasons it is not happening. You should see one declaration that lost to specificity (#checkout button scores (1,0,1) against (0,1,0)), one that is inactive (justify-content with no display: flex), one that is inactive for a different reason (width on an inline element), and a typo with a warning triangle.

Quick check
In the Styles pane, justify-content: flex-end is dimmed with an info icon, not struck through. What does that tell you?
Need a nudge? A hint rules out a wrong answer.

Device mode and what it cannot tell you

The device toolbar (Cmd+Shift+M or Ctrl+Shift+M) resizes the viewport, sets a device pixel ratio so srcset picks the right image, switches to touch events, and changes the user agent string.

Know its limits, because many "works on my machine" bugs live in them. Device mode is still Chrome's Blink engine at desktop CPU speed. It does not reproduce Safari's collapsing toolbar (the source of most 100vh bugs), the iOS zoom on inputs under 16px, rubber-band scrolling, or WebKit layout differences. The Cross-Browser CSS lesson covers those bugs. For anything that only fails on a phone, use a real device: Chrome on Android connects through chrome://inspect, and Safari on an iPhone connects to Safari Web Inspector on a Mac, as you will see below.

Network: reading a waterfall

Open the Network panel before you load the page, or reload with it open, because it only records while visible. Tick Disable cache to see what a first-time visitor downloads (it only applies while DevTools is open). The throttling menu simulates slower connections such as "Fast 4G" or "Slow 4G".

Click any request and open Timing to see where its time went.

Where one request spends its time
  1. Queueing and Stalledwaiting for a connection slot or for higher-priority requests
  2. DNS, Initial connection, SSLfirst request to a new origin only
  3. Request sentusually under a millisecond
  4. Waiting (TTFB)the server thinking, plus one round trip
  5. Content Downloadbytes arriving

Long Queueing means the browser discovered the request but chose to wait. The resource was low priority, or found late, so it lined up behind others.

1/4

The waterfall as a whole tells a story too. A hero image that starts late, after the CSS and a script, is a discovery problem. Hover the Initiator column to see what requested it. If the answer is a script or a CSS background-image, the browser could not find the image until that file loaded. Right-click the table header and add the Priority column. An LCP image marked Low usually needs fetchpriority="high" and must not have loading="lazy", as Core Web Vitals and Page Speed explained.

Four features save hours:

  • Filters. The type buttons (Fetch/XHR, JS, CSS, Img, Font) plus text filters such as larger-than:100k, -domain:*.example.com and status-code:404.
  • Request blocking. Right-click a request and choose Block request URL or Block request domain. The page reloads without it. This is how you test what happens when the analytics script, a font CDN or an API endpoint fails, before production finds out for you.
  • Copy as cURL / Copy as fetch. Right-click a request to reproduce it in a terminal or console with the same headers and body.
  • HAR export. The download arrow saves the whole session as a HAR file. Chrome offers a sanitized export by default; a HAR "with sensitive data" contains cookies and authorization headers, so never attach that one to a public ticket.

Performance: from "feels slow" to a cause

Open the Performance panel and before you record anything it shows live metrics: your local LCP and CLS for the current page load, and INP as soon as you click or type. The cards can also pull field data from the Chrome UX Report, so you can compare your fast laptop with what real users experience. When the two disagree, trust the field data and make your local setup slower until it matches.

Your laptop is several times faster than a mid-range phone, so set CPU throttling (a 4x or 6x slowdown, or a calibrated preset Chrome builds by measuring your machine) and a network preset, then click record, perform the slow interaction, and stop.

Read the recording top to bottom:

  1. The Main track is a flame chart of everything the main thread did. Wide bars are expensive. A task longer than 50ms is a long task and gets red hatching in its corner. Long tasks are what makes clicks feel sticky and INP poor.
  2. Purple "Layout" blocks with a red triangle are forced reflows. Click one and the summary shows the line of script that forced it.
  3. The Layout shifts track marks every shift, and clicking one highlights the elements that moved.
  4. The Insights sidebar groups common problems such as the LCP breakdown, render-blocking requests and layout shift culprits, and links each to the events in the trace.

Forced reflow, demonstrated

The browser normally batches layout work once per frame. If your script writes a style and then immediately reads a geometry value (offsetHeight, getBoundingClientRect(), scrollTop), the browser must run layout right now to give an accurate answer. Do that in a loop and you get layout thrashing: one layout per item instead of one per frame.

HTML & CSS
<style> .row { height: 6px; margin: 1px 0; background: #93c5fd; } button { margin-right: 8px; } #out { font-family: ui-monospace, monospace; margin: 8px 0; } #list { height: 160px; overflow: auto; border: 1px solid #ccc; }</style><button id="bad">Thrash (read, write, read, write)</button><button id="good">Batch (all reads, then all writes)</button><div id="out">Click a button.</div><div id="list"></div><script> const list = document.getElementById("list"); for (let i = 0; i < 600; i++) { const d = document.createElement("div"); d.className = "row"; list.appendChild(d); } const rows = [...list.children]; const out = document.getElementById("out"); document.getElementById("bad").onclick = () => { const t = performance.now(); for (const r of rows) { const w = r.offsetWidth; // read: forces layout r.style.width = (w === 100 ? 200 : 100) + "px"; // write: invalidates layout } out.textContent = "Thrash: " + (performance.now() - t).toFixed(1) + " ms"; }; document.getElementById("good").onclick = () => { const t = performance.now(); const widths = rows.map((r) => r.offsetWidth); // one layout rows.forEach((r, i) => { r.style.width = (widths[i] === 100 ? 200 : 100) + "px"; }); out.textContent = "Batch: " + (performance.now() - t).toFixed(1) + " ms"; };</script>

Preview

Click each button a few times. The thrashing loop is usually many times slower. Then open the Performance panel, record while clicking Thrash, and look for the purple Layout blocks with red triangles. The fix in real code is the same as in the second button: read everything first, then write, or move the writes into requestAnimationFrame.

Predict the outputJavaScript

How many times must the browser run layout synchronously in this loop over 3 items, assuming nothing was dirty before it started? Type a number.

for (const el of items) {      // 3 items
el.style.height = "20px";     // write
total += el.offsetHeight;     // read
}
Need a nudge? Hints walk you through it.

The Rendering drawer: become a different user

Press Esc in DevTools to open the drawer, then add the Rendering tab from its menu. It holds most of the emulation you need for accessibility and theming work:

  • Paint flashing tints areas green when they repaint.
  • Layout shift regions flash blue where content moves, which makes a CLS problem visible as it happens.
  • Emulate CSS media type: print previews your print stylesheet without the print dialog.
  • Emulate CSS media feature switches prefers-color-scheme, prefers-reduced-motion, prefers-contrast and forced-colors. Test your dark theme and your reduced-motion fallbacks here without changing your OS settings.
  • Emulate vision deficiencies renders the page as someone with blurred vision, protanopia, deuteranopia, tritanopia or achromatopsia would see it. If your error state is only "turns red", this shows you the problem in one click.

Lighthouse, Coverage, Overrides and Recorder

Lighthouse loads the page in a simulated mid-range phone setup and scores performance, accessibility, best practices and SEO. It is lab data: one run, one device profile, often simulated throttling. Scores vary by several points between runs, so compare medians and treat the opportunities list as the useful part. Its accessibility checks catch missing labels and low contrast, but cannot judge whether alt text makes sense or a widget works with a keyboard.

Coverage (command menu, "Show Coverage") records which bytes of each CSS and JS file actually ran. Big red bars on the main bundle point to code you could split or defer. Be careful: "unused" means unused on this page, in this state, during this session. The modal styles show as unused until you open the modal.

Local Overrides is the most underrated feature. In Sources, enable Overrides and choose a folder. Now you can edit any response, CSS, JS, HTML or even response headers, and DevTools serves your version on every reload. That lets you test a fix against production, before deploying, with real data and real third-party scripts. Right-click a request in Network and choose Override content to start quickly.

Recorder records a user flow (navigate, click, type), replays it, and can measure the replay in the Performance panel. It is a quick way to hand a teammate an exact reproduction.

Firefox and Safari do some things better

Firefox DevTools has the best Grid inspector: it overlays line numbers, line names, area names and gaps, can show several grids at once, and highlights the grid cell under your cursor. Its Flexbox inspector explains, step by step, how each item grew or shrank to its final width. Its Accessibility inspector shows the accessibility tree and checks contrast, keyboard access and missing labels.

Safari Web Inspector is the only real way to debug Safari and iOS. On a Mac, turn on Safari > Settings > Advanced > "Show features for web developers". On the iPhone, enable Web Inspector in Safari's Advanced settings (Settings > Apps > Safari > Advanced on current iOS), connect by cable the first time, and the phone appears in Safari's Develop menu. You get the full inspector on the phone's real WebKit engine, including the iOS toolbar and keyboard behaviour that device mode cannot fake.

A routine for "why is this element not where I expect?"

Most layout bugs fall to the same sequence, run in order instead of editing CSS at random.

Debugging a misplaced element
Inspect the elementright-click, InspectIs it the right element?wrapper, pseudo-element, portalComputed width and heightMargins collapsing or autoBox modelsize, padding, marginParent is grid, flex or blockOverlay the grid or flex linesLayout contextparent badgeContaining blockStacking context and z-indexPositioningposition, inset, transformStruck through or inactiveLayer and specificityStyles panewhyoverflow hidden or containOverflow and clippingancestorsroot

Confirm you selected the box you think. Many bugs are on a wrapper div, a ::before, or a portal rendered at the end of body.

1/6
Match the pairs0/5 matched

Match each question to the DevTools feature that answers it fastest.

Choose an item, then its match on the other side.
Put it in order6 steps

A click on the filter panel feels slow on mid-range phones. Put a sound investigation in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Quick check
A layout bug appears only on iPhones. Responsive mode in Chrome looks fine. What is the best next step?
Need a nudge? A hint rules out a wrong answer.
Key terms
inactive CSS
A declaration that won the cascade but has no effect in its context, such as width on an inline element. DevTools dims it and explains why.
Computed pane
Shows the final value of every property on an element and every declaration that tried to set it.
TTFB
Time to first byte: how long the browser waited between sending a request and receiving the first byte of the response.
long task
Any main-thread task over 50ms. Long tasks delay input handling and hurt INP.
forced reflow
A synchronous layout caused by reading geometry, such as offsetHeight, right after changing styles.
Local Overrides
A DevTools feature that serves your locally edited copy of a response every time the page loads.
HAR
HTTP Archive: a JSON file of a whole network session. A full HAR can contain cookies and tokens.