Skip to content Skip to sidebar Skip to footer

Css Grid : How Auto Placement Algorithm Works

I was going through the example provided in MDN article on grid-auto-flow to understand how the auto-placement algorithm works in CSS grid. Here's how the example is defined (you c

Solution 1:

If we are placing positioned items first, then in case of option set to row, why isn't explicitly placed item 4 (red) placed in the first row and 2nd column? Why does implicitly placed Blue get placed before it in second column? Also, this behavior is seemingly correct when option set to column

For this you need to refer to the specification and the full placement algorithm:

  1. Generate anonymous grid items
  2. Position anything that’s not auto-positioned.
  3. Process the items locked to a given row.
  4. Determine the columns in the implicit grid.
  5. Position the remaining grid items.

The trick is that you think your element will be placed in the step (1) but no. Your element has only one explicit rule and the other is auto so it counts as an auto-positioned element.

If we follow the rules, we have no element to position in the step (1). We have one element to position in the step (2) which is #item1 since it's locked to a given row Then all the other elements are placed in the step (4) and the document order will define the placement:

For each grid item that hasn’t been positioned by the previous steps, in order-modified document order:

You are not using the order property so the document order will be the reference.

Worth to note that the same apply to the column flow but the result was more intuitive because we first placed #item4 (column locked) then considering the document order we place the #item1 (not because this one had grid-row-start: 3;)


Why is auto-placement working differently in case of row and column values. In case of option column we start by filling columns, so why can't the first auto-placed item (item2 yellow) occupy the empty cell at row1, column1 position (like it does in case of option: row)

I think the explanation above cover this too. You need to follow the algorithm which behave differently in both cases:

To aid in clarity, this algorithm is written with the assumption that grid-auto-flow has row specified. If it is instead set to column, swap all mentions of rows and columns, inline and block, etc. in this algorithm.

Post a Comment for "Css Grid : How Auto Placement Algorithm Works"