10

I want change a div element's position [in the viewed document order] by media query.

<div>1</div>
<div>2</div>

When I change my viewport then I want to div_1 stay under the div_2. Basically div_1 on the top. But I want change it by Media query. Can it is possible??

Dan Eastwell
  • 5,146
  • 4
  • 22
  • 34
xakar
  • 125
  • 1
  • 2
  • 10

1 Answers1

22

Use flexbox and its order property

I recommend a .wrapper, though you can use it on the body as well and get the same result

@media screen and (max-width: 800px) {
  .wrapper {
    display: flex;
    flex-direction: column;
  }
  .wrapper div:first-child {
    order: 1;
  }
}
<div class="wrapper">
  <div>1</div>
  <div>2</div>
</div>

If flexbox isn't an option, you can use display: table

@media screen and (max-width: 800px) {
  .wrapper {
    display: table; 
    width: 100%; 
  }
  .wrapper div:nth-child(1) {
    display: table-footer-group; 
  }
}
<div class="wrapper">
  <div>1</div>
  <div>2</div>  
</div>
Asons
  • 84,923
  • 12
  • 110
  • 165
  • 3
    This is incredibly handy for when you want a left-right row followed by a right-left row on a wide screen, and you want the image div on top of each row on narrower screens. Your solution is great. – Altimus Prime Feb 01 '18 at 20:31
  • I just caught this question/answer and it occurred to me that you've not posted a CSS Grid solution. It didn't occur to me - until I started putting together my own answer to address that 'omission' - that CSS Grid doesn't (seem to) have a 'column-reverse' or 'row-reverse' option for `grid-auto-flow`. – David Thomas Jul 26 '19 at 13:39
  • 1
    @DavidThomas -- When posted, in Feb 2017, CSS Grid were only available through the "experimental flag" in FF/Chrome, hence no reason to show one. Today it could be, though as the only change needed to my Flexbox sample is to change to `display: grid` (and remove _flex-direction_) and it will work out of the box. When it comes to the `'*-reverse'` values, Grid doesn't have those, but they doesn't come into play with what is asked here anyway. – Asons Jul 26 '19 at 14:42
  • @DavidThomas -- Also note, when using `*-reverse` in Flexbox, it does more than just reorder the items, it changes the flow, and e.g. _flex row items_ would, with `row-reverse`, flow from right to left. – Asons Jul 26 '19 at 14:48
  • @DavidThomas Regarding reverse in CSS Grid, here's one of _Michael_B_'s great answers: https://stackoverflow.com/questions/45383042/reverse-order-of-columns-in-css-grid-layout – Asons Jul 26 '19 at 16:07
  • 1
    @LGSon: thanks, most of that I knew I was really taking the opportunity to grumble about an *arguable* lack of functionality in CSS Grid, while also observing that this answer is still about the best it could be. I hadn’t seen that question, though, or Michael_B’s answer. Thanks! – David Thomas Jul 26 '19 at 16:26