How to offset a div in a css grid
14,107
Solution 1
Consider negative margin:
.container {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-template-rows: repeat(3, 1fr);
width: 500px;
height: 200px;
border: 1px solid;
}
.box {
grid-column: 2/3;
margin-left: -20px;
margin-right: -80px;
background: red;
}
.box-alt {
grid-column: 2/3;
grid-row:2;
background: blue;
}
<div class="container">
<div class="box"></div>
<div class="box-alt"></div>
</div>
Solution 2
<div class="container">
<div class="area1"></div>
<div class="area2"></div>
</div>
.container{
display: grid;
grid-template: 1fr / repeat(3, 1fr);
grid-template-areas: "area1 offset area2";
}
.area{
width: 100%;
height: 40px;
}
.area1{
background-color: red;
}
.area2{
background-color: yellow;
}
Solution 3
If you are using Mozilla's guide in this link, you can use empty div like this as offset div:
<div class="container">
<div class="row">
<!-- Empty/Offset Div Here -->
<div class="col-xl-2"> </div>
<div class="col-xl-8">
<!-- Content Here -->
</div>
</div>
</div>
![Gianmarco](https://i.stack.imgur.com/mVLq2.jpg?s=256&g=1)
Comments
-
Gianmarco about 2 years
-
G-Cyrillus almost 6 yearsI believe the trick here is to set a template of 6 or 9 columns and play withe spanning . regular spanning 2 or 3 cols and the one looking offset spanning an extra col or stating at col 4 instead 3 ... ;)
-
Temani Afif almost 6 years@G-Cyr true but I saw it differently ... I thought he will first define the element inside the grid using row/column and then we want to add some offsets to it :)
-
d-_-b over 2 yearsdoesn't this assume using bootstrap which isn't mentioned in the original post?
-
Fezcode over 2 yearsIt doesn’t use Bootstrap, on the contrary, it replaces it with grid system.
-
d-_-b over 2 years
.col-xl-8
is defined where? -
Fezcode over 2 yearsI followed getbootstrap.com/docs/4.0/layout/grid/#grid-options for grid options value. In Mozilla’s post, it defines custom column classes, like
@media (min-width: 1200px) { .col-lg-12 { grid-column: span 12 }
Then I definedcol-xl-*
class since it is upto you to define your custom classes. -
d-_-b over 2 yearsI see - their guide also provides CSS which you may want to include.