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 can change the select option to change value of grid-auto-flow property here):
function changeGridAutoFlow() {
var grid = document.getElementById("grid");
var direction = document.getElementById("direction");
var dense = document.getElementById("dense");
var gridAutoFlow = direction.value === "row" ? "row" : "column";
if (dense.checked) {
gridAutoFlow += " dense";
}
grid.style.gridAutoFlow = gridAutoFlow;
}
#grid {
height: 200px;
width: 200px;
display: grid;
grid-gap: 10px;
grid-template: repeat(4, 1fr) / repeat(2, 1fr);
grid-auto-flow: column;
/* or 'row', 'row dense', 'column dense' */
}
#item1 {
background-color: lime;
grid-row-start: 3;
}
#item2 {
background-color: yellow;
}
#item3 {
background-color: blue;
}
#item4 {
grid-column-start: 2;
background-color: red;
}
#item5 {
background-color: aqua;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link href="/static/build/styles/samples.37902ba3b7fe.css" rel="stylesheet" type="text/css" />
<title>grid-auto-flow - Setting_grid_auto-placement - code sample</title>
</head>
<body>
<div id="grid">
<div id="item1"></div>
<div id="item2"></div>
<div id="item3"></div>
<div id="item4"></div>
<div id="item5"></div>
</div>
<select id="direction" onchange="changeGridAutoFlow()">
<option value="column">column</option>
<option value="row">row</option>
</select>
<input id="dense" type="checkbox" onchange="changeGridAutoFlow()">
<label for="dense">dense</label>
</body>
</html>
Now as far as I understand from this another article from MDN, CSS grid places items in this order:
- Explicit placement: First place all the positioned items (items1 and 4)
- Implicit or Auto-placement: Place all the other items in their order value (if any) defined in Grid. If no order defined, place them in order in which they appear in document source.
Now I have 2 major questions regarding how it works in above example:
- 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
- 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)