Daniel Daniel - 1 year ago 62
CSS Question

Achieving a certain grid using flexbox

I'm using flexbox to create a grid for my website. The grid is used for an articles archive, and should display 3 articles per row with margin between each article.

The problem is: I need the article boxes to start at the beginning of the row and end exactly at the end of the row. So the obvious thing was to use

justify-content: space-between;
, which I did. So this, in addition to
flex-wrap: wrap
created the grid I needed. Until I has a odd number of articles. Then the
property left a blank space at the middle of the row, as you can see in the following example:


It is very important to me, that no matter what the width of the container is, the items will start at the beginning and will end the the end.

How can I achieve this?

Answer Source

Flexbox doesn't support inter-item padding but we can fake it with calc() and margin. Codepen

.container {
  width: 800px;
  height: 800px;
  background-color: blue;
  display: flex;
  flex-wrap: wrap;
  /*justify-content: space-between;*/

.item {
  width: 150px;
  height: 150px;
  background-color: green;
  /* margins */
  margin-left: 10px;
  /* figure out width taking margins into account */
  flex-basis: calc((100% - 20px) / 3);
/* clear margin on every third item starting with the first */
.item:nth-child(3n+1) {
  margin-left: 0;
<div class="container">
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download