Search code examples
csscss-grid

How works CSS grid-autoflow?


I faced with the problem that I don't understand how implicit grids work. I read the documentation, MDN and a couple of resources more. But there is an open question.

.grid {
  display: grid;
  grid-template: repeat(2, 100px) / repeat(6, 1fr);
  grid-gap: 1rem;
  font-size: 2rem;
}

.grid__item {
  background-color: #BDBDBD;
}

.grid__item--1 {
  grid-row: 1 / -1;
}

.grid__item--5 {
  grid-row: 1 / -1;
}
<div class="grid">
  <div class="grid__item grid__item--1">1</div>
  <div class="grid__item grid__item--2">2</div>
  <div class="grid__item grid__item--3">3</div>
  <div class="grid__item grid__item--4">4</div>
  <div class="grid__item grid__item--5">5</div>
  <div class="grid__item grid__item--6">6</div>
</div>

And here is the result: example

Why does the fifth block go before the second?

Code: https://jsfiddle.net/serhioses/51do02xa/


Solution

  • What you want is defined in this part of the specification where we first have:

    1. Process the items locked to a given row.

    For each grid item with a definite row position (that is, the grid-row-start and grid-row-end properties define a definite grid position), in order-modified document order:

    then

    1. Position the remaining grid items.

    So basically we position the items that have an explict placement inside rows (both grid-row-start AND grid-row-end should be different from auto) then we place the other considering the algorithm described in the above specification.

    Even if you modify the order you will have the same result:

    .grid {
      display: grid;
      grid-template: repeat(2, 100px) / repeat(6, 1fr);
      grid-gap: 1rem;
      font-size: 2rem;
    }
    
    .grid__item {
      background-color: #BDBDBD;
    }
    
    .grid__item--1 {
      grid-row: 1 / -1;
    }
    
    .grid__item--5 {
      grid-row: 1 / -1;
      order:100;
    }
    <div class="grid">
      <div class="grid__item grid__item--1">1</div>
      <div class="grid__item grid__item--2">2</div>
      <div class="grid__item grid__item--3">3</div>
      <div class="grid__item grid__item--4">4</div>
      <div class="grid__item grid__item--5">5</div>
      <div class="grid__item grid__item--6">6</div>
    </div>