'Unable to set gap or margin in flex grid without overflow [duplicate]
I always used CSS grid but I found out how to make grids with flex and it's much better for my needs: a full-screen two-columns grid with a variable number of rows spreaded through the entire window. So I wrote this:
body {
margin:0;
}
container {
display: flex;
flex-wrap: wrap;
width: 100vw;
height: 100vh;
}
box {
box-sizing: border-box;
background-color: lightgray;
border: 2px solid white;
width: 50%;
padding: 10px;
border-radius: 10px;
}
<body>
<container>
<box>1</box>
<box>2</box>
<box>3</box>
<box>4</box>
<box>5</box>
<box>6</box>
</container>
</body>
Codepen here: https://codepen.io/kastaldi/pen/GROYopw
I can add or remove "box" elements and the grid adapts automatically. Unfortunately, I wasn't able to add a gap between the boxes because of overflow with CSS properties "gap" or "margin" despite the "box-sizing" so I added a fake gap using white borders. I'm not a CSS expert so I googled here and flexbox generators, but I didn't find a solution. Am I missing something ? Thanks.
Solution 1:[1]
I'd recommend you to use display:grid instead, seems like it would be better suited for this. Specially making the items responsive and having a gap between them.
Solution 2:[2]
I have had this issue in the past. If you are not worried about responsive layout I would do this:
container {
display: flex;
flex-wrap: wrap;
width: 100vw;
height: 100vh;
justify-content: center;
}
box {
box-sizing: border-box;
background-color: lightgray;
border: 2px solid white;
width: 45%;
margin: 20px;
height: 200px;
padding: 10px;
border-radius: 10px;
}
you can add or subtract margin to your liking. This works for me really well.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Javi |
| Solution 2 | Jeff |
