Justify center flexbox items without cutting off overflow

538 Views Asked by At

I have multiple flexbox containers with child divs aligned within in them.

The containers have varying numbers of child divs. Some have just one child and some have so many children that they overflow the container div, requiring a scroll.

I want the containers with just one or a few child divs to justify content from the center.

However, if there are so many divs that they overflow, I want to make sure the first item(s) does not get cut off.

I have a JSfiddle demonstrating the issue. In the first container, the first few items get cut off, but I want them to start with item one justified left. Is this possible?

.container{
    width: 100%;
    background-color: gray;
    overflow: scroll;
    display: flex;
  gap: 1em;
    justify-content: center;
}

.items{
    width: 100px;
    height: 100px;
    display: inline-block;
  flex-grow: 0;
    flex-shrink: 0;
  background-color: blue;
  color: white;
  text-align: center
}
1

There are 1 best solutions below

2
Richard Henage On

Use an outer container and an inner container.
Outer container: has justify-content: center
Inner container: has overflow: auto

.center-container{
    width: 100%;
    background-color: gray;
    display: flex;
    justify-content: center;
    margin-bottom: 50px;
}

.overflow-container{
    width: fit-content;
    max-width: 100%;
    overflow: auto;
    display: flex;
    gap: 1em;
}

.items{
    width: 100px;
    height: 100px;
    display: inline-block;
    flex-grow: 0;
    flex-shrink: 0;
    background-color: blue;
    color: white;
    text-align: center
}
<div class="center-container">
  <div class="overflow-container">
    <div class="items">Just one item</div>
  </div>
</div>
<div class="center-container">
  <div class="overflow-container">
    <div class="items">Item 1</div>
    <div class="items">Item 2</div>
    <div class="items">Item 3</div>
    <div class="items">Item 4</div>
    <div class="items">Item 5</div>
    <div class="items">Item 6</div>
    <div class="items">Item 7</div>
    <div class="items">Item 8</div>
    <div class="items">Item 9</div>
    <div class="items">Item 10</div>
    <div class="items">Item 11</div>
  </div>
</div>
<div class="center-container">
  <div class="overflow-container">
    <div class="items">Item 1</div>
    <div class="items">Item 2</div>
    <div class="items">Item 3</div>
    <div class="items">Item 4</div>
    <div class="items">Item 5</div>
    <div class="items">Item 6</div>
    <div class="items">Item 7</div>
    <div class="items">Item 8</div>
  </div>
</div>