Getting a single-block layout when grid elements span multiple columns

Using:

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

inside the grid, everything works fine. It creates as many fragments as can fit in space.

When I add an element grid-column: span 2to the grid element, everything works well until there is enough space for one element.

Because of the span 2grid, it never breaks into one column and creates an incredibly small column with the next element and never wraps.

If I pulled span 2it out , it would turn around perfectly.

I would prefer not to use a media query, if possible, to solve this problem.

Does anyone have an idea why this is happening?

Here is the code code: 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>
Run codeHide result

, , .

:)

+4
1

- , ?

, grid-column: span 2 , , . , .

, . -.

.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>
Hide result
+2

Source: https://habr.com/ru/post/1694108/


All Articles