I am a first time CSS-Grid user:
What I try to achieve is to have a flexible box system using a 3-column grid to which I can simply add boxes of the size of 1, 2 or 3 columns; just using one class.
I tried to achieve this by doing this https://codepen.io/mathil/pen/WXarXB :
.container {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
grid-gap: 12px;
width: 50%;
margin-right: auto;
margin-left: auto;
background: grey;
}
.card-fullspan {
grid-column: span 3;
}
.card-twothirdspan {
grid-column: span 2;
}
.card-thirdspan {
grid-column: span 1;
}
<div class="container">
<div class="card-fullspan" style="background: red">Fullspan</div>
<div class="card-twothirdspan" style="background:green">
twothirdspan
</div>
<div class="card-thirdspan" style="background:green">
thirdspan
</div>
</div>
I know that I have to span it for 4, which would be this for the fullspan:
.card-fullspan {
grid-column: span 4;
}
But of course this does not work with the other two, since I wont be able to come to arrive at the sum of for with a combination of the other boxes. There will always be the 12px
Gutter on the right side.
I know that it's possible to just add a different class or id to each of the items, but that wouldn't be the ideal solution.
The span
keyword counts subsequent grid lines.
So in a three column grid, when you want an item to span the full row, you specify span: 3
, not span: 4
, which creates an additional (implicit) column.
Your code:
.card-fullspan {
grid-column: span 4; /* spans across 4 columns */
}
Try this instead:
.card-fullspan {
grid-column: span 3; /* spans across 3 columns */
}
or this:
.card-fullspan {
grid-column: 1 / 4; /* spans from grid-column-line 1 to 4 (3 columns) */
}
or this:
.card-fullspan {
grid-column: 1 / -1; /* spans from grid-column-line 1 from the start side
to grid-column-line: 1 starting from the end side
(note: negative integers work only with explicit grids */
}
All the details are in the spec in this section: