Search code examples
cssflexbox

How do I change the order of divs in my responsive design while 2 of them are in a container?


I have the following layout on desktop (first screenshot):

enter image description here

For small screens, I want Div 2 first, then Div 1 and then Div 3.

The problem is that Div 2 and Div 3 are in a container div because otherwise they would not wrap but be next to each other. Because of that I can't use the order function of flexbox. I kind of have to get the divs out of the container, then I could use the order function.

This is what I tried but of course it doesn't work because Div 2 and Div 3 are locked together. (screenshot 2)

enter image description here

* {
    margin: 0;
    padding: 0;
}

.container {
display: flex;
flex-direction: row;
border: solid;
}

.div1 {
width: 400px;
height: 400px;
background-color: lightblue;
}

.div2 {
width: 300px;
height: 200px;
background-color: lightgreen;
}

.div3 {
width: 200px;
height: 100px;
background-color: rgb(238, 144, 188);
}

@media (max-width: 600px) {
.container {
  flex-direction: column;
}

.div1 {
  order: 2;
}

.div2 {
  order: 1;
}

.div3 {
    order: 3;
}
}
<div class="container">
    <div class="div1">
        <h2>Div 1</h2>
    </div>
    <div class="right-container">
        <div class="div2">
            <h2>Div 2</h2>
        </div>
        <div class="div3">
            <h2>Div 3</h2>
        </div>
    </div>
</div>


Solution

  • You can use display: contents on right-container. Its children will then be treated as part of the flex and the orders will be taken into account.

    <style>
      * {
        margin: 0;
        padding: 0;
      }
      
      .container {
        display: flex;
        flex-direction: row;
        border: solid;
      }
      
      .div1 {
        width: 400px;
        height: 400px;
        background-color: lightblue;
      }
      
      .div2 {
        width: 300px;
        height: 200px;
        background-color: lightgreen;
      }
      
      .div3 {
        width: 200px;
        height: 100px;
        background-color: rgb(238, 144, 188);
      }
      
      @media (max-width: 600px) {
        .container {
          flex-direction: column;
        }
        .div1 {
          order: 2;
        }
        .div2 {
          order: 1;
        }
        .div3 {
          order: 3;
        }
        .right-container {
          display: contents;
        }
      }
    </style>
    </head>
    
    <body>
    
      <div class="container">
        <div class="div1">
          <h2>Div 1</h2>
        </div>
        <div class="right-container">
          <div class="div2">
            <h2>Div 2</h2>
          </div>
          <div class="div3">
            <h2>Div 3</h2>
    
          </div>
        </div>
      </div>
    
    </body>
    
    </html>