htmlcssresponsive-designcss-grid

How can I split members of a subgrid when reordering (due to screen size)


I'm creating a web UI where I have one large area of main information, and three sidebar areas. Two of the sidebars are narrow, and one is wider. On a wide enough display, I want to show them like this:

wide screen display. The main content takes up a left column; on the right the two narrow sidebars sit side-by-side above the wide sidebar

On a narrow screen, I want to move everything into a single column with the narrow sidebars above the main content, and the wide sidebar underneath:

narrow screen display - there is one column of full-width panels, ordered: narrow sidebar 1, narrow sidebar 2, main content, wide sidebar

At the moment, I have the following CSS Grid arrangement for the wide view (utilising Tailwind CSS, so the classes describe the layout):

<div class="grid grid-cols-[3fr_2fr] gap-2">
  <div class="h-64 p-2 bg-amber-300">Main content</div>
  <div> <!-- prevent the right column appearing full height -->
    <div class="grid grid-cols-2 gap-2">
      <div class="h-36 p-2 bg-green-300">Sidebar 1</div>
      <div class="h-36 p-2 bg-blue-300">Sidebar 2</div>
      <div class="col-span-2">
        <div class="h-16 p-2 bg-red-300">Wide sidebar</div>
      </div>
    </div>
  </div>
</div>

Is it possible to achieve the narrow-display, single-column arrangement via, say, order? If not, how can I modify my code to achieve both layouts? I don't have to use Grid - if a different technique (eg flex-box) would allow me to get the desired result, that would be fine.


Solution

  • Here’s how you can modify your code:

    <div class="grid gap-2 
                md:grid-cols-[3fr_2fr] md:auto-rows-min">
    
      <!-- Sidebar 1 (First in narrow view, top-left of right column in wide view) -->
      <div class="h-36 p-2 bg-green-300 md:col-start-2 md:row-start-1 sm:order-1">
        Sidebar 1
      </div>
    
      <!-- Sidebar 2 (Second in narrow view, top-right of right column in wide view) -->
      <div class="h-36 p-2 bg-blue-300 md:col-start-3 md:row-start-1 sm:order-2">
        Sidebar 2
      </div>
    
      <!-- Main Content (Left column in wide view, below sidebars in narrow view) -->
      <div class="h-auto p-2 bg-amber-300 md:col-start-1 md:row-span-2 sm:order-3">
        Main content
      </div>
    
      <!-- Wide Sidebar (Spans the bottom of the right column in wide view, full-width in narrow view) -->
      <div class="h-16 p-2 bg-red-300 md:col-start-2 md:row-start-2 md:col-span-2 sm:order-4">
        Wide sidebar
      </div>
    
    </div>
    

    Seems to work.

    The layout now seems to work. See this code pen: Tailwind Layout

    Ive added comment on the codepen how I think its all working.