I have a flex container that displays two divs side by side on a normal screen.
[div1] [div2]
When they wrap on a smaller device this ends up as
[div1]
[div2]
What I want is for them to appear as
[div2]
[div1]
This is trivial if done with media queries, but I have a very dynamic layout which makes that unfeasible, and the whole reason I'm using flex box is to try to avoid tedious/unaintainable media queries.
Is there some magic combination of flex CSS properties that will give me the behaviour that I desire? I've played around quite a bit with no success, but feel this must be a relatively common CSS 'want', so hopefully someone here can answer this in seconds!
I had the exact same problem and was struggling with flex-direction
controlling the order regardless of wrapping or not. Turns out flex-wrap
has a wrap-reverse
option that does exactly what you want in this case: https://developer.mozilla.org/en-US/docs/Web/CSS/flex-wrap
It turns out that this is rather simple. Just use flex-direction:row-reverse;
https://jsfiddle.net/gveukj1j/
HTML:
<div id="container">
<div id="div2">
Div 2
</div>
<div id="div1">
Div 1
</div>
</div>
CSS:
/* the relevant CSS */
#container{display:flex;flex-wrap:wrap;flex-direction:row-reverse}
#container>div{flex-basis:400px;flex-shrink:0}
/* CSS to make the demo clear */
#container>div{line-height:200px;height:200px;color:#fff;text-align:center}
#div1{background:blue}
#div2{background:red}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With