Reputation: 6192
I have a div with elements aligned as a row, this is the css class for it:
.myRow {
display: grid;
grid-template-columns: 0.1fr 0.1fr 2fr 3fr 2fr;
grid-column-gap: 10px;
grid-row-gap: 10px;
justify-content: center;
padding: 10px;
}
<div class="myRow">
<div style="color:blue; width: 5px;">aa</div>
<div style="color:red;">bb</div>
<div style="color:green;">ccc</div>
<div style="color:orange;">ddd</div>
<div style="color:purple;">eee</div>
</div>
I want to be able to remove the first two gaps and keep the rest of the gaps, like how grid-template-columns
works.
Is it possible to do this with grid?
Edit: I want it to be like this:
Upvotes: 7
Views: 29672
Reputation: 371113
You cannot set multiple sizes for grid gaps. The column-gap
and row-gap
properties (previously grid-column-gap
and grid-row-gap
) accept only a single value.
This issue is covered in detail here:
Pseudo-elements applied to a grid container are considered grid items.
This behavior is explained here:
The order
property can be used to re-arrange grid items on the screen.
More details here:
Taken in combination, you can create the column gaps – there are only two – with ::before
and ::after
pseudo-elements, arrange their placement with the order
property, and get rid of the grid-column-gap
rule.
.myRow {
display: grid;
grid-template-columns: 0.1fr 0.1fr 2fr auto 3fr auto 2fr;
justify-content: center;
padding: 10px;
}
.myRow::before {
content: "";
width: 10px;
background-color: white;
}
.myRow::after {
content: "";
width: 10px;
background-color: white;
}
.myRow > :nth-child(1) { order: -3; }
.myRow > :nth-child(2) { order: -2; }
.myRow > :nth-child(3) { order: -1; }
.myRow > :nth-child(5) { order: 1; }
.myRow > div {
background-color: lightgray;
}
<div class="myRow">
<div style="color:blue;">aa</div>
<div style="color:red;">bb</div>
<div style="color:green;">ccc</div>
<div style="color:orange;">ddd</div>
<div style="color:purple;">eee</div>
</div>
Here's a little more about how this works:
Since the default value of the order
property is 0
, and items are then placed in source order, this is how the browser sees the nth-child
pseudo-class code above:
.myRow > :nth-child(1) { order: -3; }
.myRow > :nth-child(2) { order: -2; }
.myRow > :nth-child(3) { order: -1; } /*
.myRow > ::before { order: 0; }
.myRow > :nth-child(4) { order: 0; }
.myRow > ::after { order: 0; } */
.myRow > :nth-child(5) { order: 1; }
Upvotes: 3
Reputation: 9348
Add negative right margin whose value is equal to grid gap
.myRow {
display: grid;
grid-template-columns: 0.1fr 0.1fr 2fr 3fr 2fr;
grid-column-gap: 10px;
grid-row-gap: 10px;
justify-content: center;
padding: 10px;
}
.margin {
margin-right: -10px
}
<div class="myRow">
<div class="margin" style="color:blue; width: 5px; ">aa</div>
<div class="margin" style="color:red;">bb</div>
<div style="color:green;">ccc</div>
<div style="color:orange;">ddd</div>
<div style="color:purple;">eee</div>
</div>
Upvotes: 13