swjh
All posts

How to align in css while preserving scrollable overflow

⬪2 min read
csstil

One day we discovered out Modal component was not scrollable anymore, even though it had overflow: auto.

This confused me, but luckily my coworker found out it was because of place-content: center on the container (a simple modern way to center the modal).

But there’s a solution: For various alignment and placement properties, there’s now the safe keyword. Setting it will preserve scrollability if content overflows. Browser support is pretty good, see caniuse.com.

I wish this was the default.

From now on I’ll always use it, when I’m not 100% sure how long content.

align-items: safe center;
align-content: safe center;
place-content: safe center;
/* etc */

As Temani Afif points out, it does not only apply to flexbox and grid, but also block layout. And: setting auto margin will also have the same effect.

I’m not sure how I missed the #TIL post by Stefan Judis, explaining it nicely.