Change div order and alignment based on screen size

Issue

I would like to order my divs based on screen size using css only, and the following html that can’t be changed due to constraints:

<div class="main">
  <div class="div1">1</div>
  <div class="div2">2</div>
  <div class="div3">3</div>
</div>

When the screen size is large enough, I want to have the following format:

|<div1>|<div2>|
|      |<div3>|

ie div1 is next to both div2 and div3, and div3 is beneath div2

When the screen size is small, I want to have the following format:

|<div2>|
|<div3>|
|<div1>|

ie the divs are all underneath each other, in the order 2, 3, 1.

Thank you

Solution

I would recommend using a grid and media queries like below.

.main {
  display: grid;
  grid-template-areas: 'div2' 'div1' 'div3';
}

.div1 {
  grid-area: div1;
}

.div2 {
  grid-area: div2;
}

.div3 {
  grid-area: div3;
}

@media only screen and (min-width: 800px) {
  .main {
    grid-template-areas: 'div1 div2' '. div3';
  }
}
<div class="main">
  <div class="div1">1</div>
  <div class="div2">2</div>
  <div class="div3">3</div>
</div>

Answered By – Gerard

Answer Checked By – Senaida (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.