Search code examples
htmlcsslayoutalignment

CSS - How can I change order of DIVs based on screen size?


I have a CSS layout question. I have 3 divs aligned next to each other horizontally. like this...

div1 div2 div3

I need the divs to change order as the screen gets smaller. For example, at a certain size, they would appear like this. Div2 and 3 next to each other with div1 underneath.

div2 div3

div1

And if you get even smaller, they would appear vertical in this order...

div2

div1

div3

I was able to achieve this by using display:none and creating duplicate versions of the divs and turning them on and off based on the screen size. I hear that kind of thing is bad for SEO though. Viewing my code, google would see multiple copies of the same data a few times. Is there a better way to get this done?


Thank you for telling me about ORDER. I'm getting close. Now I need the DIV labeled TEXT to appear centered under the other 2 divs at 1200 width. And then everything centered vertical at 800 width.

#container {
display: flex;flex-flow: row wrap;justify-content: center;gap:50px 25px;
}

#div1 {width :150px;border:1px solid red;order:1;display:block}
#div2 {width :150px;border:1px solid red;order:2;display:block}
#div3 {width :150px;border:1px solid red;order:3;display:block}


@media (max-width: 1200px) {
#div1 {order:3;}
#div2 {order:1;}
#div3 {order:2;}
}


@media (max-width: 800px) {
#div1 {order:2;}
#div2 {order:1;}
#div3 {order:3;}
}
<div id="container">


<div id="div1">
TEXT
</div>

<div id="div2">
Image
</div>

<div id="div3">
VIDEO
</div>



</div>


Solution

  • Like the comment suggested. You can use flexbox with order property to achieve it. But you may also consider using grid layout for more percise control

    .container {
      display: grid;
      grid-auto-flow: column dense;
      justify-content: center;
      justify-items: center;
      gap: 8px;
    }
    
    .container .item {
      width: 150px;
      padding: 10px;
      border: solid 1px currentColor;
    }
    
    @media screen and (width < 1200px) {
      .container .item:nth-child(1) {
        grid-row: 2;
        grid-column: 1 / span 2;
      }
    }
    
    @media screen and (width < 800px) {
      .container .item:nth-child(1) {
        grid-column: initial;
      }
      
      .container .item:nth-child(3) {
        grid-row: 3;
      }
    }
    <div class="container">
      <div class="item">TEXT</div>
      <div class="item">Image</div>
      <div class="item">Video</div>
    </div>