Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS Grid - Transitioning from 1 row, 3 col to 3 row, 1 col

I'm exploring CSS Grid to see if it can completely replace the need for responsive CSS media queries for my specific use case. I have the following grid container:

.gridContainer {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    padding: 0px 15px;
    margin: 0 auto;
    grid-row-gap: 20px;
}

The grid container holds three items that initially result in one row and three columns on larger screen sizes:

enter image description here

When I reduce the viewport width such that the three columns are below 250px each, I would like the grid layout to snap to a layout of three rows and one column:

enter image description here

As you reduce the viewport width, there is currently an interim layout where the third item wraps onto a row where it sits by itself, due to the auto-placement algorithm selected:

enter image description here

I would like to bypass this wrapping and only support the initial one-row, three-column layout and the final three-row, one-column layout. Is this possible with CSS Grid only and without the use of media queries?

like image 875
Shandy Avatar asked Sep 16 '25 10:09

Shandy


1 Answers

You may use a mediaquerie and turn your container into a grid once a minimal width is reach : (code option taken since you gave so little infos)

basis example of the idea

div {
  padding: 1em;
  margin: 1em;
  border: dotted tomato;
}

@media (min-width: 780px) {
  body {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    padding: 0px 15px;
    margin: 0 auto;
    grid-row-gap: 20px;
  }
}
<div>lorem</div>
<div>lorem</div>
<div>lorem</div>

You can play the snippet in full page mode and resize your browser to check out the behavior.

like image 79
G-Cyrillus Avatar answered Sep 18 '25 09:09

G-Cyrillus