Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting to a one-column layout when grid items span multiple columns

Tags:

html

css

css-grid

When using:

grid-template-columns: repeat(auto-fit, minmax(*size*, 1fr));

inside of a grid, everything seems to work perfectly. It creates as many tiles as can fit in the space.

When I add a grid-column: span 2 to a grid item everything works well until there is only enough space for one item.

Because of the span 2 the grid never breaks down to just one column, and creates an incredibly small column with the following item and never wraps.

If I take out the span 2, it wraps perfectly.

I'd rather not use a media query if possible to address this behavior.

Does anybody have any insight as to why this happens?

Here is a Codepen of the behavior: https://codepen.io/anoblet/pen/BYOeQM

.grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(450px, 1fr));
}

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

.grid-auto {
  background: red;
}

.grid-900 {
  max-width: 850px;
  background: blue;
}
<div class="grid grid-auto">
  <div>1</div>
  <div>2</div>
  <div class="span-2">3</div>
  <div>4</div>
  <div>5</div>
</div>
<div class="grid grid-900">
  <div>1</div>
  <div>2</div>
  <div class="span-2">3</div>
  <div>4</div>
  <div>5</div>
</div>

Both grids will display the behavior if you resize the window, though the second one will display it right away.

Thanks for the help :)

like image 772
Andrew Noblet Avatar asked Oct 16 '22 22:10

Andrew Noblet


1 Answers

Does anybody have any insight as to why this happens?

Because when you set grid-column: span 2 on an item it forces the item to span two columns, regardless of screen size. In your code, there is no reason for this item to span one column.

You need to tell the item to switch from two columns to one when the screen resizes. Media queries exist for this purpose.

revised codepen

.grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(450px, 1fr));
  background: red;
}

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

@media ( max-width: 500px ) {
  .grid   { grid-template-columns: 1fr; }
  .span-2 { grid-column: span 1;        }
}
<div class="grid">
  <div>1</div>
  <div>2</div>
  <div class="span-2">3</div>
  <div>4</div>
  <div>5</div>
</div>
like image 123
Michael Benjamin Avatar answered Oct 31 '22 13:10

Michael Benjamin