HeadlinesBriefing favicon HeadlinesBriefing.com

Centering a Div in Browsers with Sidebars

Hacker News •
×

Centering a div used to require a ritual involving absolute positioning and transforms. These days, it is almost disappointingly easy using display: grid and place-items: center. However, new challenges arise when browsers add sidebars. A div might look perfectly centered, but it is actually centered inside the wrong rectangle.

Initial attempts to fix this involved calculating the difference between window.innerWidth and window.outerWidth. This worked until Dev Tools was opened, which changes the width difference without revealing how the total is split between sides. To find the missing coordinate, the solution relies on pointer events. A pointer event knows where it is on the screen versus inside the webview.

By calculating the difference between event.screenX and event.clientX, the exact position of the viewport within the window can be located. While Firefox exposes this directly, Chromium requires the site to start with an estimate and correct it once the pointer enters the page. This logic powers "center, actually," a tool designed to find centered elements even on pages you do not control.