Search code examples
htmlcssmedia-queries

Div's stack on top of each other, just not in right order


I have a couple divs, placed side by side and using a media query to stack them, which they do stack but I need the yellow one to be on top and the blue below it. So opposite of what you see when the script is ran and not sure on how to do it.

#wrapper {
    width:1000px;
}
#mydivLeft {
    background:blue;
    height:250px;
    width:50%;
    float:left;
}

#mydivRight {
    background:yellow;
    height:250px;
    width:50%;
    float:right;
}

@media only screen and (max-width:768px){
    #wrapper {
        width:100%;
    }

    #mydivRight, #mydivLeft {
        display:block;
        float:none;
        width:100%;
    }

}
<body>
    <div id="wrapper">
        <div id="mydivLeft">
        </div>
        <div id="mydivRight">
        </div>
    </div>
</body>


Solution

  • You can just reverse the order of the divs in the HTML to be whatever order you want them to be.

    #wrapper {
        width:1000px;
    }
    #mydivLeft {
        background:blue;
        height:250px;
        width:50%;
        float:left;
    }
    
    #mydivRight {
        background:yellow;
        height:250px;
        width:50%;
        float:right;
    }
    
    @media only screen and (max-width:768px){
        #wrapper {
            width:100%;
        }
    
        #mydivRight, #mydivLeft {
            display:block;
            float:none;
            width:100%;
        }
    
    }
    <div id="wrapper">
      <div id="mydivRight">
      </div>
      <div id="mydivLeft">
      </div>
    </div>

    Alternatively, a more complicated solution is to use flexbox, and use the order property or flex-direction: column-reverse; to re-order the flex children.

    #wrapper {
      width: 1000px;
      display: flex;
    }
    
    #wrapper > div {
      width: 50%;
      height: 250px;
    }
    
    #mydivLeft {
      background: blue;
    }
    
    #mydivRight {
      background: yellow;
    }
    
    @media only screen and (max-width:768px) {
      #wrapper {
        width: auto;
        flex-direction: column-reverse;
      }
      #wrapper > div {
        width: auto;
      }
    }
    <div id="wrapper">
      <div id="mydivLeft">
      </div>
      <div id="mydivRight">
      </div>
    </div>