Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to change the order of flex items when they wrap, without using a media query?

Tags:

html

css

flexbox

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!

like image 493
Codemonkey Avatar asked Dec 14 '16 11:12

Codemonkey


2 Answers

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

like image 150
nip3o Avatar answered Nov 20 '22 08:11

nip3o


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}
like image 41
Codemonkey Avatar answered Nov 20 '22 07:11

Codemonkey