Search code examples
htmlcssgridalignmentcenter

How to center align a grid of divs in a flex container?


I am trying to centre align the 3 column grid (which is made up of 6 flex- items) placed in a flex-container div. (Refer to image attached)

I tired many variations of float and align-content. I also tried to place the flex items in a sub container but couldn't make it work.

This is what I currently have:

.flex-container {
  flex-direction: row;
  display: -webkit-flex;
  display: inline-flex;
  background-color: #f5f7f9;
  width: 100%;
  align-content: center;
  flex-flow: row wrap;
  margin-top: 100px;
}
.flex-item {
  width: 23%;
  height: 360px;
  margin: 10px;
  order: 1;
  border-radius: 3px;
  padding: 0 10px 40px 10px;
}
.colour-1 {
  background-color: #8c72cb;
}
.colour-2 {
  background-color: #54c7ec;
}
.colour-3 {
  background-color: #a3cedf;
}
.colour-4 {
  background-color: #b9cad2;
}
.colour-5 {
  background-color: #6bcebb;
}
.colour-6 {
  background-color: #a3ce71;
}
<div class="flex-container">
  <div class="flex-item colour-1"></div>
  <div class="flex-item colour-2"></div>
  <div class="flex-item colour-3"></div>
  <div class="flex-item colour-4"></div>
  <div class="flex-item colour-5"></div>
  <div class="flex-item colour-6"></div>
</div>

IMAGE

Thanks.


Solution

  • You can use justify-content on the flex container to align items over its main axis. Take a look at this example: https://jsfiddle.net/eL650y3e/

    Sources: