Skip to content
Tech News
← Back to articles

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

read original more articles
Why This Matters

This article highlights the evolving challenges of centering elements in web design, especially with the addition of browser sidebars and UI elements. It underscores the importance of adaptive techniques that account for dynamic browser chrome and user interactions, which are crucial for creating consistent, user-friendly layouts across devices and browsers.

Key Takeaways

Centering a div used to require this little 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 used that for the .site div you’re reading. It looked centered until I opened it in a browser with the sidebar visible.

The .site div was still perfectly centered, just inside the wrong rectangle. I figured the fix would be simple enough: JavaScript knows the width of both the webview and the browser window.

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

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

const shift = - browserChrome / 2;

. site { translate : var ( --window-center-shift , 0px); }

... continue reading