Search code examples
javascripthtmlcsscss-grid

Not able to position 4th element in second row using css grid


Problem - I want to keep the 4th box in 2nd row like in the current code, but the width of the 4th box should be similar to 1/2/5/6 box i.e. 100px.

But currently 4th box is taking full width in 2nd row, I want it to take only 100px space and rest empty space in row 2. 5 and 6 ox should come on 3rd row.

Alignment Needed -

1 2 3
4
5 6
7 7 7

Code -

.one { background: red; }
.two { background: green; }
.three { background: blue; }
.four { background: pink; }
.five { background: violet; }
.six { background: yellow; }
.seven { background: teal; }
.box { padding: 5px; text-align: center; }
.container {
  border: 1px solid;
  display: grid;
  grid-template-columns: 100px 100px auto;
  gap: 20px 10px;
}

.box:nth-child(4) {
  grid-column: span 3;
}

.box:last-child {
  grid-column-end: span 3;
}
<div class="container">
  <div class="box one">1</div>
  <div class="box two">2</div>
  <div class="box three">3</div>
  <div class="box four">4</div>
  <div class="box five">5</div>
  <div class="box six">6</div>
  <div class="box seven">7</div>
</div>


Solution

  • How about directly setting the column start and ends? (Mainly for the 5th)

    .one { background: red; }
    .two { background: green; }
    .three { background: blue; }
    .four { background: pink; }
    .five { background: violet; }
    .six { background: yellow; }
    .seven { background: teal; }
    .box { padding: 5px; text-align: center; }
    .container {
      border: 1px solid;
      display: grid;
      grid-template-columns: 100px 100px auto;
      gap: 20px 10px;
    }
    
    .box:nth-child(4) {
      /*grid-column: span 1;*/
      grid-column-start: 1;
      grid-column-end: 2;
    }
    .box:nth-child(5) {
      grid-column-start: 1;
      grid-column-end: 2;
    }
    
    .box:last-child {
      grid-column-end: span 3;
    }
    <div class="container">
      <div class="box one">1</div>
      <div class="box two">2</div>
      <div class="box three">3</div>
      <div class="box four">4</div>
      <div class="box five">5</div>
      <div class="box six">6</div>
      <div class="box seven">7</div>
    </div>