I was trying to learn how to change the order of columns on a very simple grid (grid-template-columns: 1fr 1fr
). The answer was quite simple: add the following rule to the second item: grid-row-start: 1; /* grid-row: 1; shortcut also works */
.
_________ _________
| A | B | --> | B | A |
--------- ---------
But I can't understand why this works. I'm trying to change the order of columns but I'm using row rules? The second item is already in the first row. What changed after adding that rule?
I tried to make sense of it. I reset the grid and added grid-column-start: 1;
to the second item. I ended up with this grid:
_________
| A | | #B { grid-column-start: 1; }
---------
| B | |
---------
After that, I added grid-column-start: 2;
to the first item and the result was:
_________
| | A | #A { grid-column-start: 2; }
--------- #B { grid-column-start: 1; }
| B | |
---------
Now, I have to tell the second item to start at the first row: grid-row-start: 1;
and I finally got what I wanted.
_________
| B | A | #A { grid-column-start: 2; }
--------- #B { grid-column-start: 1; grid-row-start: 1; }
But the thing is, I can keep only grid-row-start: 1;
and achieve the same result! Why?!
body {
background: lightgoldenrodyellow;
}
#content {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
}
h2 {
text-align: center;
}
.grid {
display: grid;
width: 480px;
height: 240px;
margin: 4rem auto;
grid-template-columns: 1fr 1fr;
gap: 5px;
font-size: 3rem;
}
.column {
border: black solid 1px;
}
.colorA {
background: turquoise;
text-align: center;
}
.colorB {
background: aliceblue;
text-align: center;
}
.column3 {
/* does nothing */
display: block;
}
.column4 {
grid-row-start: 1;
}
.column5 {
/* does nothing */
display: block;
}
.column6 {
grid-column-start: 1;
}
<div id="content">
<div>
<h2>Original</h2>
<div class="grid">
<div class="column colorA column1">A</div>
<div class="column colorB column2">B</div>
</div>
</div>
<div>
<h2>Using grid-row-start</h2>
<div class="grid">
<div class="column colorA column3">A</div>
<div class="column colorB column4">B</div>
</div>
</div>
<div>
<h2>Using grid-column-start</h2>
<div class="grid">
<div class="column colorA column5">A</div>
<div class="column colorB column6">B</div>
</div>
</div>
</div>
grid-auto-flow:row
is the default behavior, if you reset it togrid-auto-flow:row dense
, it will fill the empty cells else it will distribute items through the grid cells after cells. Take also a look atorder
to reorder grid or flex items (#B{order:-1}
)order
default is0
.