·10 min read

getBoundingClientRect wrong after CSS scale

I scaled every screen of my game with CSS transform scale. Two measurements inside it went wrong: a grid lost a column, and a drag lagged the finger.

cssjavascriptwebgamedev

Contents

Picture Word Connect broke on small phones. Popups ran on under the ad banner, ribbon titles went off the edge of the screen, and a 320-wide phone wrapped button labels onto two lines. My first round of fixes was a set of tiers: below this width use smaller buttons, below that height use a tighter gap. It mostly worked, and I threw it away the same evening, because it was a list of hand-picked pixel values that the next phone size would need another entry in.

What replaced it is one composition. Every screen except the board is laid out once, at the 390×844 it was designed for, and then drawn smaller or larger with a CSS transform: scale() to fit the room left between the system bars and a 100dp banner. A small phone shows the same home screen, smaller. A tablet shows it larger, instead of phone-sized in the middle of the glass.

The scale each screen ended up at, measured in Chrome with the banner in place:

Viewport Home Settings Shop Win screen
320×568 0.59 0.76 0.80 0.80
360×640 0.65 0.85 0.92 0.92
375×667 0.73 0.95 0.96 0.96
390×844 0.90 1.00 1.00 1.00
412×915 1.00 1.00 1.00 1.00

That part went fine. The trouble was everything inside the scaled screen that measured itself. A CSS transform scale makes getBoundingClientRect return a different size from offsetWidth and clientWidth, and two pieces of code mixed them up.

Why I used a transform and not zoom

CSS zoom would also have shrunk the screens. I chose transform: scale because the game flies things across the screen — a found word, a hint — and every one of those flights reads where things are from getBoundingClientRect. Under a transform, that function answers with where the element actually shows on the page, so the flights could stay as they were.

I did not try zoom to compare, so I can't tell you it would have broken them. That was the reasoning, and it is also exactly what bit me next.

The levels grid lost its last column

I captured every screen at 11 viewport sizes: 7 phones from 320×568 to 430×932, each with the banner, and 4 portrait tablets from 768×1024 to 1024×1366. Home, settings and the shop came out right everywhere. The levels screen did not. On a 375-wide phone and on every tablet, the last column of level tiles ran off the right edge.

The levels screen lays out its grid from the size of its container. That size came from our shared layout package, whose measure function does this (simplified):

// Simplified from a shared layout helper.
measure() {
  const rect = element.getBoundingClientRect();
  // fractional and reflects transforms; clientWidth is an integer and does not
  return { width: rect.width || element.clientWidth, height: rect.height || element.clientHeight };
}

The comment is accurate, and on an unscaled page it is the better choice. Inside a scaled screen it is the bug. getBoundingClientRect is the box as drawn, after the scale. The grid then lays its tiles out in the container's own pixels, and the browser applies the scale to them a second time. On a tablet, where the scale is above 1, the grid was laid out for a box wider than the one it had, then drawn larger again, and the last column landed off screen.

The 375-wide phone is scaled down, not up, so the same arithmetic does not obviously push it over. I did not trace exactly why that one size tipped and its neighbours did not. The fix below cured it along with the tablets, and the before and after screenshots are all I have on it.

How to get the scale of an element

The scale an element is drawn at is its drawn width over its layout width. offsetWidth ignores transforms, so the ratio is the scale of every transformed ancestor combined:

// Simplified: an element's size in its own layout pixels, even under a scaled ancestor.
function layoutSize(element) {
  const drawn = element.getBoundingClientRect();           // after transforms
  const scale = element.offsetWidth > 0 && drawn.width > 0
    ? drawn.width / element.offsetWidth                    // drawn ÷ laid out
    : 1;                                                   // not laid out yet
  return { width: drawn.width / scale, height: drawn.height / scale };
}

Dividing gives back the layout width, still fractional. That is why I kept the rect rather than switching to offsetWidth: the shared helper preferred the rect for its fractions, and I did not want to lose them only to fix the scale. The guard matters too — jsdom and an element that is not laid out yet both report zero, and a zero divisor turns the size into NaN.

The correction went into the one hook the levels grid measures with, wrapped around the shared function rather than changed inside it. The board screen is not scaled, and it measures as it always did.

After the change every phone showed the same 4 whole columns and the tablets showed 5 or 6. All 485 of the game's tests passed, which they had before the fix as well. The screenshots were the only thing that told the two versions apart.

The same bug in a pan/zoom component

The same night I moved Picture Word Connect's board onto our shared pan/zoom package. Reading its pointer code to check it against the new scaled screens, I found the same mix in a different place:

// Simplified: the shape of the bug, not the package's code.
const box = canvas.getBoundingClientRect();               // page pixels, after the scale
const local = { x: e.clientX - box.left, y: e.clientY - box.top };
viewport.resize(canvas.clientWidth, canvas.clientHeight); // layout pixels, before it

The viewport worked in the canvas's layout pixels. The pointer positions went in as page pixels. On an unscaled page those are the same thing, which is why nothing had caught it. Inside a screen drawn at 60%, a finger moving 50 page pixels was applied as 50 of the canvas's own, which the scale then draws as 30. The board would move 60% as far as the finger, and a pinch or wheel zoom would centre on the wrong point because the pointer's offset was too large by the same factor.

Those last two sentences are arithmetic, not a measurement. The game screen is not one of the scaled ones, so no player could hit this, and I did not build a broken version to film it. What I did measure is the fixed one.

The fix is one helper that every conversion goes through, in both directions:

// Simplified: page coordinates to an element's own pixels, and back.
function placementOf(el) {
  const r = el.getBoundingClientRect();
  const sx = r.width > 0 && el.offsetWidth > 0 ? r.width / el.offsetWidth : 1;
  const sy = r.height > 0 && el.offsetHeight > 0 ? r.height / el.offsetHeight : 1;
  // the content starts inside the border, and the border is scaled too
  return { left: r.left + el.clientLeft * sx, top: r.top + el.clientTop * sy, sx, sy };
}
const toLocal = (p, x, y) => ({ x: (x - p.left) / p.sx, y: (y - p.top) / p.sy });
const toPage = (p, pt) => ({ x: p.left + pt.x * p.sx, y: p.top + pt.y * p.sy });

Drag, pinch, the wheel's pan distance, and the public methods that take or return page positions all go through it. It measures on every call instead of caching, so a screen that re-fits when the banner loads is picked up on the next touch.

Testing it when jsdom has no layout

jsdom does not lay anything out. getBoundingClientRect returns zeros there, so a unit test can only describe a scaled canvas by stubbing the rect. I added four tests that do that: a canvas 400×400 in its own pixels, drawn at 200×200, 10 px in and 20 px down the page. A drag of 25 page pixels has to move the view 50 of the canvas's own. A page point has to map to content and back. Zooming to an element has to use its size in content units. The wheel has to pan as far as it turned on the page. The suite went to 83 tests, all passing.

A stub is only my own idea of the geometry played back to me, so I ran the playground in real Chrome and WebKit through Playwright, with its phone frame wrapped in transform: scale(0.6). The first run reported a failure:

Chrome  FAIL a drag follows the finger on a 60% screen — content moved 124.2 own px = 74.5 page px for a 50 px drag

That was not the fix. The playground had fling turned on, so after the mouse came up the board kept coasting, and the measurement caught the coast. With inertia switched off for that check:

Chrome  ok   a drag follows the finger on a 60% screen — content moved 83.3 own px = 50.0 page px for a 50 px drag
Chrome  ok   zoomToElement centres it on the scaled frame — tile middle (132.0, 216.0), frame middle (132, 216)
Chrome  ok   the wheel zooms about the pointer — content under the pointer now at (172.0, 246.0)
WebKit  ok   a drag follows the finger on a 60% screen — content moved 83.3 own px = 50.0 page px for a 50 px drag
WebKit  ok   zoomToElement centres it on the scaled frame — tile middle (132.0, 216.0), frame middle (132, 216)
WebKit  ok   the wheel zooms about the pointer — content under the pointer now at (172.0, 246.0)

83.3 × 0.6 is 50. The board follows the finger at any scale, and the point under the cursor stays under it while zooming. The unscaled browser and touch checks from before still passed, so the helper changed nothing at a scale of 1. It went out as a patch release, and the game moved to it.

The zoom buttons on that board had a CSS bug of their own the same night: they drew over the game's popups. That one was a stacking context, and it is written up in CSS z-index not working with position: fixed.

Takeaway

Inside an element with transform: scale, there are two sets of pixels. getBoundingClientRect, clientX and clientY are in page pixels, after the transform. offsetWidth, clientWidth and everything you set in CSS are in layout pixels, before it. Each is right on its own. The bug is a formula that takes one from each, and on an unscaled page that formula gives the right answer, so nothing complains until something gets scaled.

When you scale a whole screen, search everything inside it for getBoundingClientRect and decide which set of pixels each call needs. Both of mine were found by screenshots and by reading the code, not by the unit tests, which passed throughout. I have only ever scaled. A rotate would make the drawn width a bounding box rather than a scaled width, and the ratio above would no longer be the scale; I have not tested what it does there.

More posts

New writing when there is something worth saying. By email or by RSS, whichever you prefer.