Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 283
DevStacker Avatar asked Jul 10 '15 14:07

DevStacker


2 Answers

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>
like image 98
Stickers Avatar answered Oct 12 '22 23:10

Stickers


Considering that you don't want swap them. Here is the fiddle: https://jsfiddle.net/c8x49afg/ Just use position relative for divs pulling the second up and pushing the first down.

.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 {
    position: relative;
    top: 110px;
    width: 100%;
  }
  .two {
    position: relative;
    top: -100px;
    width: 100%;
  }
}
<div class="wrapper">
  <div class="one">
    one
  </div>


  <div class="two">
    two
  </div>
</div>
like image 36
Giacomo Cerquone Avatar answered Oct 13 '22 01:10

Giacomo Cerquone