Creating a smart layout with CSS flex

28th April, 2018 - 1 min. read - in Tutorials - Go to Index

Sometimes I use this blog to remind me some technique I learned time ago. I cannot keep everything in my memory, thus, I need to download some stuff somewhere. This blog serves also for that!

This is why I’m going to document this little technique I learned to solve a specific layout need for a personal project both for my personal annotation as well as in the hope it might be useful to someone else.

My problem was: how to keep some content centered vertically in a given wrapper BUT if that content gets bigger the aforementioned wrapper would be so nice to provide a scrollbar?

This looks a no-brainer problem with CSS flex, isn’t it?

The first, and most obvious attempt, failed. Using a flex wrapper with justify-content:center property was not enough:

See the Pen not smart layout by Fabio Franchino (@abusedmedia) on CodePen.

For some reason, the content, the moment it needs more space, is placed outside the top side of the wrapper making impossibile to reach the top portion of the content itself.

After a bit of trial and error, I’ve ended up with a working solution, with an additional flex wrapper:

See the Pen smart layout by Fabio Franchino (@abusedmedia) on CodePen.

The trick here has been separating the wrapper that is responsible to center the whole content from the one that is responsible to distribute each single items.

Spotted a typo or (likely) a grammar error? Send a pull request.