Search code examples
cssmedia-queries

Using css media queries to re-arrange elements


I'm a relative novice with CSS. I have a header bar on my site that looks like this: enter image description here

I'm using media queries to adjust it for narrow displays. I've got the menu bar to compact into a single dropdown and shrunk the logo, but I want to re-order the elements so they look like this: enter image description here

I can't find a way to make this work - I need to contain the title and menu bar within a div to group them together in the first version, which means I can't arrange them as shown in the second version.

Is there a system of divs that can produce the top layout and the bottom layout, changing only the CSS and not the HTML?


Solution

  • You can solve this easily with CSS grids. In the snippet below, if you press Expand snippet you will see the full version.

    I wasn't sure if the "shrunk menu" should be off grid like your graphic, but in case it's not needed, you just need to remove the width property on the media query.

    .wrapper {
      display: grid;
      grid-template-columns: 100px 270px;
      grid-template-rows: 57px 32px;
      grid-gap: 12px;
      grid-template-areas: 
        "logo header"
        "logo menu";
    }
    
    .wrapper > div {
      outline: 4px solid black;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    
    .logo {
      grid-area: logo;
    }
    
    .header {
      grid-area: header;
    }
    
    .menu {
      grid-area: menu;
    }
    
    @media (max-width: 700px) {
      .wrapper {
        grid-template-columns: 83px 213px;
        grid-template-rows: 57px 32px;
        grid-gap: 14px 9px;
        grid-template-areas: 
          "logo header"
          "menu .";
      }
      .menu {
        width: 100px;
      }
    }
    <div class="wrapper">
      <div class="logo">Logo</div>
      <div class="header">Page Title/header</div>
      <div class="menu">Menu Bar</div>
    </div>