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>
2
Answers
Yes, there is a better way to achieve this responsive layout without duplicating content and using display: none. You can use CSS Flexbox or CSS Grid to create a responsive layout that reorders the divs based on the screen size.
Here’s an example using CSS Flexbox:
In this example, the container uses display: flex to create a flex container, and flex-wrap: wrap allows the items to wrap to the next line when there isn’t enough space. The media query (@media (max-width: 600px)) sets the flex-basis of the items to 100%, making them stack vertically on smaller screens.
You can adjust the media query breakpoint and styles according to your specific design requirements. This approach ensures a cleaner and more SEO-friendly code compared to duplicating content.
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