Search code examples
csscss-grid

Move only one item in CSS Grid


Okay i know i can move my blocks using grid-template-areas or order. But my question is: can i move only one item to another place without changing order of every other block? Because that is a few lines more of code and i wonder if it can be made easier? I have a grid:

grid-template-rows: repeat(3, 1fr);
grid-template-columns: repeat(2, 1fr);

I want the item on the 1-st column and 1-st row to change position to 2-nd column and 1-st row. To switch places with the other block.


Solution

  • Simply specify the position using grid-column (and grid-row if needed) and make sure to use grid-auto-flow:dense to avoid empty areas:

    .box {
      display:grid;
      grid-template-rows: repeat(3, 1fr);
      grid-template-columns: repeat(2, 1fr);
      grid-auto-flow: dense;
      grid-gap:10px;
    }
    
    .box * {
      height:50px;
      background:red;
      color:#fff;
    }
    <div class="box">
      <div style="grid-column:2">1</div>
      <div>2</div>
      <div>3</div>
      <div>4</div>
      <div>5</div>
      <div>6</div>
      <div>7</div>
    </div>