skip to Main Content

I’m working on a CSS Grid-based layout system and I want to generate offset classes. For example, a ".col-offset-1" class would instruct the element to place itself at the start of the second column along from the previous element.

I’ve been experimenting with grid-column-start and I thought grid-column-start: span 2; would do the trick in a similar way to how grid-column-end works, but it doesn’t. The element still starts on the column defined by its implicit placement and then spans 2 columns instead.

The tricky bit here is I want this to be dynamic, so I can’t use specific grid line references to place things manually. I’m looking for a solution that will take whatever implicit column-start placement an element was due to have and move it along by ‘X’ columns.

See image for reference:
The intended result

I’m looking for a rule that I could apply to one class to use on both the blue elements and achieve this layout where both skip the column they were due to start on.

2

Answers


  1. What you want to achieve is not possible but you can simulate it if you play with width:

    .container {
      display: grid;
      grid-template-columns: repeat(8,1fr);
      gap: 10px;
    }
    
    .container > div {
      background: lightblue;
      height: 50px;
    }
    .container > div.offset {
      grid-column:span 2; /* take 2 columns */
      width: calc((100% - 10px)/2); /* take the width of one column */
      margin-left: auto; /* get placed at the second column */
      
      background: red;
    }
    <div class="container">
      <div></div>
      <div></div>
      <div class="offset"></div>
      <div></div>
      <div class="offset"></div>
      <div></div>
    </div>
    Login or Signup to reply.
  2. There is a possibility to get this, using 2 levels of grid children.

    However, it uses subgrid, that is fully suported in Firefox and Safari.

    .container {
      display: grid;
      grid-template-columns: repeat(8,1fr);
      gap: 10px;
    }
    
    .container > div {
      height: 50px;
      border: solid 2px gray;
    }
    
    .container > div > div  {
      background: lightblue;
      height: 50px;
    }
    
    .offset {
        display: grid;
        grid-column: span 2;
        grid-template-columns: subgrid;
    }
    
    .offset > div {
      grid-column: 2;
    }
    <div class="container">
      <div><div>ONE</div></div>
      <div><div>TWO</div></div>
      <div class="offset"><div>XXX</div></div>
      <div><div>3</div></div>
      <div class="offset"><div>Y</div></div>
      <div><div>4</div></div>
      <div><div>xxx</div></div>
      <div><div>xxx</div></div>
      <div><div>xxx</div></div>
      <div><div>xxx</div></div>
      <div><div>xxx</div></div>
      <div><div>xxx</div></div>
      <div><div>xxx</div></div>
      <div><div>xxx</div></div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search