Search code examples
htmlcssresponsive

Responsive section by columns


im trying to make a responsive section.

this is how i want it to look in desktop:

+---+---+---+--------------+
| 3 | 2 | 1 |       A      |    <- this is right one
+---+---+---+--------------+

an this is how it should look in mobile view:

+-----------+
|     A     |
+---+---+---+   <- this is right one
| 3 | 2 | 1 |
+---+---+---+

tried some tutorials too but every time ending up to this:

+-----------+
|     A     |
+-----------+
|     1     |
+-----------+   <- this is wrong one
|     2     |
+-----------+
|     3     |
+-----------+

hope visualization helps.

i tried to make a section with 2 columns. first column has letter in it. second column has a inner section with 3 column and each column has a number in it.


Solution

  • could be done with grid.

    one way would be to make nested grid, but simpler if you specify exactly position start and end.

    body {
      margin: 0;
      padding: 0;
      width: 100vw;
      height: 100vh;
    }
    
    #grid {
      display: grid;
      grid-template-rows: 1fr;
      grid-template-columns: 16.6% 16.6% 16.6% 1fr;
      gap: 0;
      width: 100%;
      height: 100%;
    }
    
    #div1 {
      grid-area: 1 / 3 / 2 / 4;
      background-color: rgba(29, 145, 229, 0.5);
    }
    
    #div2 {
      grid-area: 1 / 2 / 2 / 3;
      background-color: rgba(1, 16, 21, 0.5);
    }
    
    #div3 {
      grid-area: 1 / 1 / 2 / 2;
      background-color: rgba(66, 202, 43, 0.5);
    }
    
    #A {
      grid-area: 1 / 4 / 2 / 5;
      background-color: rgba(53, 69, 26, 0.5);
    }
    
    @media screen and (max-width: 768px) {
      #grid {
        display: grid;
        grid-template-rows: 1fr 1fr;
        grid-template-columns: 1fr 1fr 1fr;
        gap: 0;
        width: 100%;
        height: 100%;
      }
      #div3 {
        grid-area: 2 / 1 / 3 / 2;
        background-color: rgba(143, 196, 214, 0.5);
      }
      #div2 {
        grid-area: 2 / 2 / 3 / 3;
        background-color: rgba(126, 56, 58, 0.5);
      }
      #A {
        grid-area: 1 / 1 / 2 / 4;
        background-color: rgba(158, 192, 23, 0.5);
      }
      #div1 {
        grid-area: 2 / 3 / 3 / 4;
        background-color: rgba(9, 129, 51, 0.5);
      }
    }
    <div id="grid">
      <div id="div1">1</div>
      <div id="div2">2</div>
      <div id="div3">3</div>
      <div id="A">A</div>
    </div>