0

I have a container div with many child div having fixed width. I am using flexbox to align the child divs in a single row. Below html and css works except that the first and last child are still overflowing the container div. I want the child divs to be wrapped in single row using a horizontal scroll -

.container {
  display: flex;
  justify-content: center;
  width: 500px;
  height: 200px;
  background-color: gray;
  overflow-x: auto;
}

.child {
  margin: 5px;
  min-width: 100px;
  height: 150px;
  background-color: darkgray;
}
<div class="container">
  <div class="child"> </div>
  <div class="child"> </div>
  <div class="child"> </div>
  <div class="child"> </div>
  <div class="child"> </div>
  <div class="child"> </div>
</div>

Please see this codepen I've created.

Temani Afif
  • 245,468
  • 26
  • 309
  • 415
Akash
  • 4,412
  • 4
  • 30
  • 48
  • remove `justify-content: center;` from `.container` class.. i think problem will be solve – نور Oct 30 '20 at 06:09
  • Thanks @noor! After removing `justify-content: center;`, the last element is still overflowing. And the number of child divs is dynamic. I want to center align them if the container has only few children. – Akash Oct 30 '20 at 06:12
  • 1
    You said *I want the child divs to be wrapped in single row using a horizontal scroll*. Isn't your code already doing that? – Frank Fajardo Oct 30 '20 at 06:21
  • Html and css works except that the first and last child are still overflowing the container div. This. – Akash Oct 30 '20 at 06:22

1 Answers1

1

You should wrap all children into other tag to display full content without overflow

.container {
  display: flex;
  width: 500px;
  height: 200px;
  overflow: auto;
}
.flex-box {
  display: flex;
  justify-content: center;
  background-color: gray;
  flex: 1;
}

.child {
  margin: 5px;
  min-width: 100px;
  height: 150px;
  background-color: darkgray;
}
<div class="container">
  <div class="flex-box">
    <div class="child"> </div>
    <div class="child"> </div>
    <div class="child"> </div>
    <div class="child"> </div>
    <div class="child"> </div>
    <div class="child"> </div>
  </div>
</div>
Wolf
  • 9,679
  • 7
  • 62
  • 108