Matho Matho - 2 months ago 11
CSS Question

How to center a Flex list container with wrap and justify to flex-start elements

I have some issues implement Flex-box, in my requirement for a view I have a list of cards, each card has a default width and height. I can use flex box and I prefer it.
When the elements of the list don't fit in the row, they should wrap in a new one, always from the left to the right, and all the list be centered in the available space of the container.

Here is a plunker of the layout and the code:



.list {
display: flex;
flex-grow: 0;
flex-shrink: 1;
flex-direction: row;
justify-content: flex-start;
flex-wrap: wrap;
}
.item {
width: 200px;
height: 300px;
border: 1px solid black;
background-color: #e6e6e6;
margin: 12px;
}

<body>
<div class="list">
<div class="item">someItem01</div>
<div class="item">someItem02</div>
<div class="item">someItem03</div>
<div class="item">someItem04</div>
<div class="item">someItem05</div>
</div>
</body>





This is what I'm trying to achieve:
enter image description here

And this is what I currently have:
enter image description here

How can I achieve the this without recurring to bunch of media queries, hard-coded margin/padding, etc?

Answer

It's not a very neat HTML, but you can achieve this result with some filler elements:

.list {
  display: flex;
  flex-grow: 0;
  flex-shrink: 1;
  flex-direction: row;
  justify-content: center;
  flex-wrap: wrap;
}
.item {
  width: 200px;
  height: 300px;
  border: 1px solid black;
  background-color: #e6e6e6;
  margin: 12px;
}

.filler {
  width: 200px;  
  margin: 12px;
}
<body>
  <div class="list">
    <div class="item">someItem01</div>
    <div class="item">someItem02</div>
    <div class="item">someItem03</div>
    <div class="item">someItem04</div>
    <div class="item">someItem05</div>
    <div class="filler"></div>
    <div class="filler"></div>
    <div class="filler"></div>
  </div>
</body>