0

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.

kastaldi
  • 1
  • 1

2 Answers2

-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.

Javi
  • 23
  • 6
-1

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.

Jeff
  • 1
  • 3
  • Thanks for the suggestion but I didn't want to use "magic numbers" such as guessing the right width percentage less than 50% because in real life 2 columns should be 50% width and I have to try again when I will have to increase the number of columns (4 columns should be less than 25%) and so on... Having never used flex before, I was thinking the gap property would fit in the container. I also tried flex-grow but it doesn't work when the number of cells is odd and I have to add an invisible box. – kastaldi Mar 01 '22 at 08:51