Search code examples
cssresponsive-designresponsiveness

Div re-order with CSS


Does anybody know of any examples or tutorials on how to achieve the below:

On desktop the layout will be: Desktop layout

On mobile the layout will change to: Mobile Layout

As you can see, I want box 2 and box 3 to re-order and swap positions on mobile

Does anybody have any tips or advice?


Solution

  • Depending on what browsers you need to support you could use the flex-box. Using a media query for screen size you could then set the order of the second and third boxes to switch below a certain screen width.

    I've done a pen with a short example. I'd also recommend the CSS Tricks Complete Guide to Flexbox which talks about how to use flex far better than I can.

    EDIT:

    The basic principle would be to set the parent element (e.g., container) to display: flex ; this generates the flexbox and allows you to set different parameters for the children.

    Using the following HTML:

    <div class="container">
      <div class="box first">
        Box 1
      </div>
      <div class="box second">
        Box 2
      </div>
      <div class="box third">
        Box 3
      </div>
    </div>
    

    If I set display:flex on .container, I can then set whether the content should display in a row or column, should wrap down a line, have space between or around the elements, etc. I've set the main rule to be a wrapping row using flex-flow (which is a shorthand for two other flex properties, including flex-direction which I need later), with space between the elements.

    .container{
      display:flex;
      flex-flow: row wrap;
      justify-content:space-between;
    }
    

    I then use a media query so when the browser is narrower than a specified width, the flex-direction gets changed from row to column

    @media screen and (max-width:600px){
      .container {
        flex-direction:column
      }
     }
    

    Then, in the same media query, I need to tell the elements that I want to re-order what order they should be in:

    @media screen and (max-width:600px){
      .container {
        flex-direction:column
      }
      .second{
        order: 3;
      }
      .third{
        order: 2
      }
    }
    

    Sometimes I've noticed that order needs to be defined for all the elements, so you might need to set it for the first block and keep it as order: 1 . From the pen linked to above, it doesn't seem to be the case here, but it something to keep an eye out for in other projects.