Search code examples
csslayoutsass

Having a 3 divs layout. How can I make the middle div to stay below the other two?


I was searching a way to make a responsive design like so I have 3 divs inside a parent div

<div style="display: flex">
  <div class="logo">some image here</div>

  <div class="menu-items">
    <a href="/home">Home</a>
    ...
  </div>

  <div class="login-logout">Here is the login component</div>
</div>

How can I make a responsive version of this to be something like this using only css and sass?

<div style="display: flex; flex-direction: column">
  <div style="display: flex">
    <div class="logo">some image here</div>

    <div class="login-logout">Here is the login component</div>
  </div>

  <div class="menu-items">
    <a href="/home">Home</a>
    ...
  </div>
</div>

I want the middle div to stay bellow the other two

I have a guess that this can be possible using grid layout, but honestly I don't understand very much about it and prefer using flex. So if this could be achieved using flex I would be very much appreciated

Edit: An image of how I want the layout to be. layout


Solution

  • flex is basically one dimensional whereas grid allows layout in two dimensions.

    This snippet takes your code but sets the container to display grid.

    grid-template areas are laid out for the wider screens in the ratio 2/3/1 and in the narrower ones in the ratio 2/1 in the top line.

    Obviously you'll want to set the relative sizes suitable for your particular case.

    .container {
      width: 100vw;
      display: grid;
      grid-template-columns: repeat(6, 1fr);
      grid-template-areas: 'logo logo menu menu menu login';
      gap: 2vw;
      padding: 2vw;
      box-sizing: border-box;
    }
    
    .container>* {
      border: 3px solid;
      box-sizing: border-box;
    }
    
    @media (max-width: 768px) {
      .container {
        grid-template-columns: repeat(3, 1fr);
        grid-template-areas: 'logo logo login' 'menu menu menu';
      }
    }
    
    .logo {
      grid-area: logo;
    }
    
    .menu-items {
      grid-area: menu;
    }
    
    .login-logout {
      grid-area: login;
    }
    
    
    /* borders added fordemo */
    
    .logo {
      border-color: red;
    }
    
    .menu-items {
      border-color: blue;
    }
    
    .login-logout {
      border-color: green;
    }
    <div class="container">
      <div class="logo">some image here</div>
    
      <div class="menu-items">
        <a href="/home">Home</a> ...
      </div>
    
      <div class="login-logout">Here is the login component</div>
    </div>