(function(d, w, timeout) {
var flexcontainer = '.flex',
flexitem = '.optional',
minwidth = 600,
classname = 'mobileview';
function resizeing() {
if ((minwidth && (minwidth < w.innerWidth)) ||
(!minwidth && (w.innerHeight < w.innerWidth))) {
if (!(d.body.classList.contains(classname))) {
d.body.classList.add(classname);
var fca = qSA(flexcontainer);
for (var i = 0; i < fca.length; i++) {
fca[i].parentNode.appendChild(qS(flexitem, fca[i]))
}
}
} else {
if (d.body.classList.contains(classname)) {
d.body.classList.remove(classname)
var fca = qSA(flexcontainer);
for (var i = 0; i < fca.length; i++) {
fca[i].appendChild(qS(flexitem, fca[i].parentNode))
}
}
}
}
w.addEventListener("load", function() {
resizeing();
}, false);
w.addEventListener("resize", function() {
if (!timeout) {
timeout = setTimeout(function() {
timeout = null;
resizeing();
}, 66);
}
}, false);
var qSA = function(s, el) {
return (el) ? el.querySelectorAll(s) :
d.querySelectorAll(s)
},
qS = function(s, el) {
return (el) ? el.querySelector(s) :
d.querySelector(s)
};
}(document, window));
html, body {
margin: 0;
}
.wrapper .flex {
flex-grow: 1;
display: flex;
flex-direction: column;
}
.wrapper .flex > div {
flex-grow: 1;
border: 1px solid;
box-sizing: border-box;
}
.wrapper .flex .optional {
order: 1;
}
.wrapper .flex .main2 {
order: 2;
}
.mobileview .wrapper {
display: flex;
}
.mobileview .wrapper .optional {
flex-basis: 25%;
order: -1;
border: 1px solid;
box-sizing: border-box;
}
<div class="wrapper">
<div class="flex">
<div class="main">A</div>
<div class="optional">
B as a lot more content<br>
B as a lot more content<br>
B as a lot more content<br>
B as a lot more content<br>
B as a lot more content<br>
</div>
<div class="main2">C</div>
</div>
</div>
<h5>More than one container and other text etc.</h5>
<div class="wrapper">
<div class="flex">
<div class="main">
A as a lot more content<br>
A as a lot more content<br>
A as a lot more content<br>
A as a lot more content<br>
A as a lot more content<br>
</div>
<div class="optional">B</div>
<div class="main2">C</div>
</div>
</div>