Baleb
Baleb

Reputation: 753

Equal margin space for flex items that wrap in flexbox grid

I am trying to create a responsive grid with flexbox:

My code so far:

.grid {
  display: flex;
  flex-wrap: wrap;
}
.gridColumn {
  flex: 1 1 0px;
  background-color: lightblue;
  min-width: 200px;
}
<div class="grid">
  <div class="gridColumn">
    <p>first column</p>
  </div>
  <div class="gridColumn">
    <p>second column</p>
  </div>
  <div class="gridColumn">
    <p>third column</p>
  </div>
</div>

Now, I would like to set margins only between the columns (not on the sides of the grid as well), which should also behave correctly when the screen is resized. Does anybody know of a way to achieve this?

Upvotes: 3

Views: 1705

Answers (2)

alanbuchanan
alanbuchanan

Reputation: 4173

You can add a margin to the grid items...

.gridColumn {
    margin: $margin;
}

... which is then offset by its container.

.grid {
    margin: -$margin;
}

To avoid overflow, you could apply overflow-x: hidden to the body.

Codepen example

Upvotes: 4

Malwurf
Malwurf

Reputation: 1

It's crashed on this part of code

.gridColumn + .gridColumn { margin-left: 20px; }

You should to try use media query and set margin-left: 0; on small screens.

Above part of code is still working because flex-wrap only changing the position of the "third column", that column still have "sister" before and margin-left is working.

Upvotes: 0

Related Questions