DEV Community

Cover image for Centering flex items with overflow
Martin Ratinaud
Martin Ratinaud

Posted on

Centering flex items with overflow

Have you ever tried scrolling horizontally a list of flex items that are justify-center and end up with the first item not shown or partially hidden.

Well, it just happened to me while working on staking crypto.

Visual description of problem and solution

Well this is very annoying, but fortunately enough, here is the solution to this problem in 3 simple steps.

For Tailwind

  1. Remove justify-center from the parent element
  2. Apply ml-auto to the first element
  3. Apply mr-auto to the last element

Tailwind having great utility classes, this can just be done in one step

  • Replace justify-center by [&>*:first-child]:ml-auto [&>*:last-child]:mr-auto

Here is a Playground

For CSS

  1. Remove justify-content:center from the parent element
  2. Apply margin-left: auto to the first element
  3. Apply margin-right: auto to the last element

Who am I?

My name is Martin Ratinaud and Iā€™m a freelance senior software engineer and remote enthusiast, contagiously happy and curious.
I create websites like this one for staking crypto and many more...

Also, I'm always looking for new challenges or MVP to create. Hire me !

Top comments (0)