I have the following HTML:
<div class="grid">
<div class="special-1"></div>
<div class="special-1"></div>
<div class="special-2"></div>
<div class="special-2"></div>
<div class="special-2"></div>
<div class="special-2"></div>
<div class="special-2"></div>
<div class="special-2"></div>
</div>
.special-1
is always in the first column. The number of .special-2
s is variable, generated by user data. So approximately:
.grid {
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-auto-rows: 1fr;
}
.special-1 {
grid-column-start: 1;
}
Now the thing is, I want .special-2
to always be in at least the second column. But it can also show in the third or fourth. Is there anyway I can do this? grid-column-start: 2;
doesn't work because it will put all of them in column 2 and none in the other columns. So I basically want grid-column: :not(1)
or grid-column: 2 | 3 | 4
if you know what I mean. Any ideas?
The answer by Temani Afif surely works, but isn't very scalable. In my usecase there's some different column counts for different viewport sizes. I eventually decided to implement this differently. Note: if by the time you read this CSS Grid Level 2 has been released, this could trivially be solved using css subgrid: caniuse
Now for my solution: I changed my html as such:
<div class="grid">
<div class="special-1s"
<div class="special-1"></div>
<div class="special-1"></div>
</div>
<div class="special-2s">
<div class="special-2"></div>
<div class="special-2"></div>
<div class="special-2"></div>
<div class="special-2"></div>
<div class="special-2"></div>
<div class="special-2"></div>
</div>
</div>
And my css now looks somewhat like below. I forced the rows to a fixed height, which was okay in my use case and made this solution possible.
.grid {
display: flex;
}
.grid > div {
display: grid;
grid-auto-rows: 100px;
}
.special-1s {
flex: 1;
grid-template-columns: 1fr;
}
.special-2s {
--columns: 2;
flex: var(--columns);
grid-template-columns: repeat(var(--columns), 1fr);
@media (min-width: 1000px) {
--columns: 3;
}
}
By using the flex
-property, I can fake consistent column-sizes across the width of .grid
. The --columns
property allows me to easily define extra media-queries. (I actually have a few more than shown here.)