2

I have a parent div element containing several children. The parent div is contained inside an outer container div. I want the parent div to be centered inside the container but the problem is that the parent uses flex-wrap: wrap to wrap all of its child divs.

The parent div is centered in the container as expected:

#container {
  width: 500px;
  display: flex;
  justify-content: center;
  background-color: #c0faff; 
}

#parent {
 display: flex;
 flex-wrap: wrap;
}

.child {
 background-color: #5bb4bb;
 width: 100px;
 height: 100px;
 margin: 5px;
}
<div id="container">
  <div id="parent">
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
  </div>
</div>

But, as soon as there is 1 child that must be wrapped onto the 2nd row, the parent div floats to the left and ignores the container's justify-content: center; css property:

#container {
  width: 500px;
  display: flex;
  justify-content: center;
  background-color: #c0faff; 
}

#parent {
 display: flex;
 flex-wrap: wrap;
}

.child {
 background-color: #5bb4bb;
 width: 100px;
 height: 100px;
 margin: 5px;
}
<div id="container">
  <div id="parent">
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
  </div>
</div>

How can I make the previous code snippet's result look like this?:

enter image description here

Mayron
  • 2,146
  • 4
  • 25
  • 51

1 Answers1

3

You can only achieve this if you set a fixed width to the container that holds the flexbox-items. You can make it a bit simpler and use calc(...) function in CSS here. If you know how many items should be in one row, you can just change the number for multiple breakpoints easily. Even easier if you set the width of one item as a css custom property.

#container {
  width: 500px;
  display: flex;
  justify-content: center;
  background-color: #c0faff; 
}

#parent {
 display: flex;
 flex-wrap: wrap;
 width: calc(4* 110px)
}

.child {
 background-color: #5bb4bb;
 width: 100px;
 height: 100px;
 margin: 5px;
}
<div id="container">
  <div id="parent">
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
  </div>
</div>
cloned
  • 6,346
  • 4
  • 26
  • 38
  • thanks @cloned, that doesn't help me for my situation but it is a solution for some so I'll approve. I really needed the dynamic width to work but it looks like such a solution does not exist with the constraints of flexbox. – Mayron Jun 23 '21 at 10:54
  • you can try using grid here. I can't think of a solution from the top of my head, but maybe you will find something that suits you. – cloned Jun 23 '21 at 11:16