简体   繁体   中英

Equal margin space for flex items that wrap in flexbox grid

I am trying to create a responsive grid with flexbox:

  • On large screens, there should be three columns in one row
  • On smaller screens, just two rows or one

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM