Search code examples
csscss-grid

Css-grid: how to add block and make other elements move up?


I have 2 condition of layout.

(1) layout-one

(2) layout-two

I want to dynamically delete or add block 2 and switch between layouts. Is it possible to deal with it via css-grid?


Solution

  • CSS grid is intended to define grid layouts.

    Il will allow you to define as many layouts as you want, but you will not be able to switch between layouts by relying only on CSS grids.

    You will have to handle it programmatically, or by using other CSS features (like media queries, if you want layout selection based on screen width).

    A way to do this is to define the grid layouts with specific CSS classes on the grid container, and switch between the classes using an external script (or a condition based on the state of your app if it's already there).

    Demo : https://jsbin.com/jolupoguni/1/edit?html,css,js,output

    JS :

    const toggleLayout = () => {
    var element = document.getElementById("grid");
      if (element.classList.contains('grid--layout-1')) {
         element.classList.remove('grid--layout-1');
         element.classList.add('grid--layout-2');
       } else {
         element.classList.remove('grid--layout-2');
         element.classList.add('grid--layout-1');
       }
    }
    

    CSS :

    .grid {
      display: grid;
      grid-template-columns: repeat(12, 1fr);
    }
    
    .grid--layout-1 .block-a {
      grid-column: span 12;
    }
    .grid--layout-1 .block-b {
      grid-column: span 6;
    }
    .grid--layout-1 .block-c {
      grid-column: span 6;
    }
    
    .grid--layout-2 .block-a {
      grid-column: span 12;
    }
    .grid--layout-2 .block-b {
      display: none
    }
    .grid--layout-2 .block-c {
      grid-column: span 12;
    }
    

    HTML

    <button onclick="toggleLayout()">Switch layout</button>
    <div id="grid" class="grid grid--layout-1">
      <div class="block block-a">Block A</div>
      <div class="block block-b">Block B</div>
      <div class="block block-c">Block C</div>
    </div>
    

    For more information about CSS grids, Wes Bos' CSS Grid course is a fantastic resource https://cssgrid.io/