Search code examples
javascripthtmlcssmedia-queries

Using media query and show a div below another div which is written before


Hello all what i am trying to do is that i have a HTML page where i have 2 divs div1 and div2 both are float left and obviously div1 comes before div2 but what i want is that with the help of media query i want div1 to get below div2 as soon as page size gets below 400px

@media only screen and (max-width: 400px) {
  .div1,
  .div2 {
    width: 100%;
  }
}
<div style="float:left;width:50%;height:100%;" class='div1'>//1

</div>
<div style="float:left;width:50%;height:100%;" class='div2'>//2

</div>

The code is right but the div comes before div2 i want div2 to come before div1 .

can anyone please suggest me something . this is just a test html i have more divs in page.


Solution

  • You can do with CSS3 flexbox layout.

    1. Wrap a parent container over the two elements. Set flex display and direction to be column(for vertical placement)
    2. Reorder your first div to be second element using order: 2

    @media (max-width: 800px) { /* Change this to 400px, 800px for demo purpose */
      .wrapper {
        display: flex;
        flex-direction: column; /* For vertical placement of items */
      }
      .div1 {
        order: 2;
      }
    }
    <div class="wrapper">
      <div style="float:left;width:50%;height:100%;" class='div1'>
        1
      </div>
      <div style="float:left;width:50%;height:100%;" class='div2'>
        2
      </div>
    </div>