Scroll or center-align based on available space
The Solution at a Glance
- Enable scrolling in the flex container by setting
overflow: auto
oroverflow: scroll
. - Make all flex items reachable by scrolling by keeping the default
: flex-start
on the flex container. - Center flex items with
auto
margins.
Enable scrolling in the flex container
Normally, any flex items that overflow the flex container will simply be visible. Instead, we want to hide those overflowing flex items, and we want to be able to reach them by scrolling within the flex container.
We’ll do that by setting overflow: auto
or overflow: scroll
on the flex container.
Make all flex items reachable by scrolling
We want to center our flex items inside the flex container when there’s space left.
Let’s try setting : center
on the flex container. This will center-align the flex items, which is what we want when there’s plenty of space.
But when there’s little space, the flex items are still center-aligned, and we have flex items overflow on each side of the flex container.
In this case, the flex items that overflow the start of the flex line can’t be reached be scrolling. They’re completely inaccessible.
This means we need the flex container to leave the initial : flex-start
alone for the scrolling to work.
Center flex items with auto
margins
Aside from alignment properties, there’s one more way to move the visible part of flex items inside the flex container: margins.
We can use an auto
margin on the first flex item on the side that “touches” the edge of the flex container. And one on the last flex item on the side that touches the flex container.
auto
margins only expand if there’s unused space. So if there’s plenty of unused space, each of the two auto
margins will grow, effectively centering the visible part of our flex items!
If there’s no unused space and the flex items overflow the flex container, the auto
margins will be zero. And the default : flex-start
will align our flex items to the start of the flex line. And they will be scrollable.