Search code examples
htmlcsscss-grid

Dynamic grid row structure


I'm trying to implement a css-grid with a dynamic structure. When an element in any row is clicked a dynamic full width row should be displayed. See the image below.

Is this kind of behaviour even possible with css grid? Any suggestions that could take me in the right direction is highly appreciated!

enter image description here


Solution

  • This can be achieved by putting the info relating to each item immediately after it in the HTML, setting it to display none and on click setting it to display.

    The whole is in a 3 column grid, with the even items set to column 1 and a span of 3.

    This snippet illustrates this on hover as we do not have the information on what should happen on a click with previously clicked items.

    .container {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      grid-auto-flow: dense;
      gap: 10px;
    }
    
    .container>div {
      display: none;
      height: 200px;
    }
    
    .container>div:nth-child(odd) {
      background: pink;
      display: block;
    }
    
    .container>div:nth-child(odd):hover+div {
      display: block;
      grid-column: 1 / span 3;
    }
    <div class="container">
      <div></div>
      <div>the stuff below item 1</div>
      <div></div>
      <div>the stuff below item 2</div>
      <div></div>
      <div>the stuff below item 3</div>
      <div></div>
      <div>the stuff below item 4</div>
    </div>