Search code examples
htmlcsscss-grid

Grid item collapsing on smaller screen size


I have a set of children inside a display: grid container - each child is numbered. At the 600px breakpoint, child 4 completely loses composure and deflates to its inner content size. Why doesn't 4 hop on down below 3?

.box {
  background: yellow;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 48px;
  font-weight: bold;
}

.box.md {
  grid-column: span 2;
}

.box.lg {
  grid-column: span 2;
  grid-row: span 2;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  grid-auto-rows: 240px;
  grid-auto-flow: dense;
  grid-gap: 8px;
}

@media (max-width: 920px) {
  max-width: 800px;
}

@media (max-width: 600px) {
  grid-auto-rows: 120px;
}
<div class="container">
  <div class="box lg">1</div>
  <div class="box md">2</div>
  <div class="box sm">3</div>
  <div class="box sm">4</div>
</div>

https://jsfiddle.net/amw273vq/


Solution

  • Why doesn't 4 hop on down below 3?

    Because items 1 & 2 both have grid-column: span 2 applied. Meaning there are two columns already available, and item 4 has no reason to move to the next row.

    Make all columns take a full row.

    Add this to your code:

    @media (max-width: 600px) {
      .container > div {
        grid-column: span 1 !important; (you need to override the span 2 rules higher up)
      }
    }
    

    revised demo


    And the reason for the collapse of item 4 has nothing to do with your media query.

    If you look closely, you'll find the item 4 collapses when the screen width is 640px. This is before the 600px media query is reached.

    enter image description here

    Here's the issue:

    grid-template-columns: repeat(auto-fit, minmax(280px, 1fr))
    

    At 640px screen width, item 3 reaches 280px, the minimum width it can be.

    As a result, item 4 is pushed to the second column, which was created by grid-column: span 2 on its siblings.

    However, at this screen size, there is only space for one explicit (i.e., defined) column. The second column must be generated in the implicit (i.e., undefined) grid.

    And, because the default value of grid-auto-columns – the property that sizes implicit columns – is auto, the second column takes the width of the widest cell.

    enter image description here