skip to Main Content

I have a grid riddle, which seems to be simple, but I just have no idea and two AI chats failed as well.
I have this:

.cont {
  display: grid;
  gap: 20px;
  grid-template-columns: repeat(auto-fit, minmax(min(150px, 100%), 1fr));
 }
.box {background-color: grey;}
<div class="cont">
<div class="box">one</div>
<div class="box">two</div>
<div class="box">three</div>
<div class="box">four</div>
</div>

What I need, is for the boxes to always be full available width and in two (and only two) columns, unless the screen gets too small and the box would get smaller than 150px, in which case switch to one column. Without the use of media queries.
The written rule "grid-template-columns" is just one of the things I tried, it’s a classic (got from Kevin Powell) that’s great, if you allow for any number of columns on wider display.
If you can achieve the same with flex, I guess that’s fine too.

2

Answers


  1. This can be achieved using flexbox:

    .cont {
      display: flex;
      flex-wrap: wrap;
      gap: 20px;
    }
    
    .box {
      background-color: grey;
      flex: 1 0 calc(50% - 10px);
      min-width: 150px;
    }
    <div class="cont">
      <div class="box">one</div>
      <div class="box">two</div>
      <div class="box">three</div>
      <div class="box">four</div>
    </div>
    Login or Signup to reply.
  2. You need max() not min() and a value that is a little bigger than 100%/3 to make sure you have less than 3 items per row (so 2 items)

    .cont {
      display: grid;
      gap: 20px;
      grid-template-columns: repeat(auto-fit, minmax(max(150px, 34%), 1fr));
     }
    .box {background-color: grey;}
    <div class="cont">
    <div class="box">one</div>
    <div class="box">two</div>
    <div class="box">three</div>
    <div class="box">four</div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search