Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS grid: two columns, unless smaller than 150px

Tags:

html

css

css-grid

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.

like image 512
maeros Avatar asked Oct 19 '25 11:10

maeros


1 Answers

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>
like image 167
Temani Afif Avatar answered Oct 21 '25 03:10

Temani Afif



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!