htmlcssresponsive-designmedia-queries

How to change side by side divs to stack on mobile?


I am trying to get my 2 divs (which are side by side) to change to stacked divs when viewed on mobile as shown in the fiddle, but I would like "two to be on top and "one" to be second.

Here is the code - http://jsfiddle.net/d3d4hb3t/

.one {
  border: 1px solid green;
  width: 29%;
  float: left;
  height: 100px;
}

.two {
  border: 1px solid blue;
  width: 69%;
  float: right;
  height: 100px;
}

@media (max-width: 767px) {
  .one {
    width: 100%;
  }
  .two {
    width: 100%;
  }
}
<div class="one">one</div>
<div class="two">two</div>

I know the simple solution would be to swap divs one and two around, but since the code I have is complicated, I was hoping there was an easier solution using just CSS.


Solution

  • Update

    Added a flexbox approach below:

    UPATED JSFIDDLE

    .wrap {
      display: flex;
    }
    
    .one {
      width: 30%;
      border: 1px solid green;
    }
    
    .two {
      width: 70%;
      border: 1px solid blue;
    }
    
    @media (max-width: 767px) {
      .wrap {
        flex-direction: column-reverse;
      }
      .one,
      .two {
        width: auto;
      }
    }
    <div class="wrap">
      <div class="one">1</div>
      <div class="two">2</div>
    </div>

    Original answer

    If you're stuck with the markup, you can still use the magic css table layout to change the order of the 2 divs. I updated it all, just to keep the consistency.

    How those display values work, from MDN:

    display: table; - behaves like <table> element.

    display: table-cell; - behaves like <td> element.

    display: table-header-group; - behaves like <thead> element.

    display: table-footer-group; - behaves like <tfoot> element.

    UPDATED JSFIDDLE

    .wrap {
      display: table;
      border-collapse: collapse;
      width: 100%;
    }
    
    .one,
    .two {
      display: table-cell;
    }
    
    .one {
      width: 30%;
      border: 1px solid green;
    }
    
    .two {
      width: 70%;
      border: 1px solid blue;
    }
    
    @media (max-width: 767px) {
      .one {
        display: table-footer-group;
        width: 100%;
      }
      .two {
        display: table-header-group;
        width: 100%;
      }
    }
    <div class="wrap">
      <div class="one">1</div>
      <div class="two">2</div>
    </div>