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>
Share:
14,107
Gianmarco
Author by

Gianmarco

javascript and reactjs enthusiast.

Updated on June 12, 2022

Comments

  • Gianmarco
    Gianmarco about 2 years

    It's possible to "offset" a div in a css grid as in the image ?image

  • G-Cyrillus
    G-Cyrillus almost 6 years
    I 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
    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
    d-_-b over 2 years
    doesn't this assume using bootstrap which isn't mentioned in the original post?
  • Fezcode
    Fezcode over 2 years
    It doesn’t use Bootstrap, on the contrary, it replaces it with grid system.
  • d-_-b
    d-_-b over 2 years
    .col-xl-8 is defined where?
  • Fezcode
    Fezcode over 2 years
    I 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 defined col-xl-* class since it is upto you to define your custom classes.
  • d-_-b
    d-_-b over 2 years
    I see - their guide also provides CSS which you may want to include.