We finally learned to center a div, then browsers added sidebars

Aug 05, 2026 05:24 AM - 2 hours ago 1

Centering a div utilized to require this small ritual:

.thing { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); }

These days, it is almost disappointingly easy:

body { display: grid; min-height: 100dvh; place-items: center; }

I utilized that for the .site div you’re reading. It looked centered until I opened it successful a browser pinch the sidebar visible.

The .site div was still perfectly centered, conscionable wrong the incorrect rectangle. I figured the hole would beryllium elemental enough: JavaScript knows the width of some the webview and the browser window.

window.innerWidth // the webview window.outerWidth // the full browser window const browserChrome = window.outerWidth - window.innerWidth;

With the sidebar connected the left, I could move .site backmost by half of that difference:

const shift = -browserChrome / 2; .site { translate: var(--window-center-shift, 0px); }

That worked, correct up until I opened DevTools.

Mine is docked connected the right, truthful the width quality now included browser UI connected some sides. It gave maine the total, but nary measurement to show really that full was split.

What yet gave maine the missing coordinate was the pointer. A trusted pointer arena knows wherever it is connected the surface and wherever it is wrong the webview, which is capable to find the webview wrong the window:

const viewportLeft = event.screenX - event.clientX * scale; const viewportRight = viewportLeft + innerWidth * scale; const left = viewportLeft - window.screenX; const right = window.screenX + outerWidth - viewportRight; const shift = (right - left) / (2 * scale);

Firefox exposes the aforesaid viewport position directly. Chromium does not, truthful this tract starts pinch the left-sidebar estimate and corrects it arsenic soon arsenic the pointer enters the page.

I wanted to effort the aforesaid hole connected pages I do not control, truthful I made center, actually. It tries to find the centered constituent itself; if it guesses wrong, I tin prime one. The demo is the simplest spot to spot the difference.

More