Change Div Order with CSS Based on Device Width
When creating responsive websites, it's common to encounter challenges in managing the order of elements as the screen size changes. While simple solutions exist for two or three divs, ordering becomes more complex with an increasing number of elements.
To address this issue, CSS's flexbox spec offers a powerful solution using the order and flex-flow properties. These properties allow for flexible ordering of elements while maintaining their inline-block display.
The following solution satisfies the requirements mentioned in the question:
HTML Structure:
<div class="container"> <div class="one">I'm first</div> <div class="two">I'm second</div> <div class="three">I'm third</div> <div class="four">I'm fourth</div> <div class="five">I'm fifth</div> </div>
CSS Styles:
.container div { width: 100px; height: 50px; display: inline-block; } .one { background: red; } .two { background: orange; } .three { background: yellow; } .four { background: green; } .five { background: blue; } @media screen and (max-width: 531px) { .container { display: flex; flex-flow: column; } .five { order: 1; } .four { order: 2; } .three { order: 3; } .two { order: 4; } .one { order: 5 } }
This solution ensures that when the screen width becomes too narrow, the divs rearrange themselves based on the specified order, while maintaining their inline-block layout and retaining their content and dimensions.
The above is the detailed content of How Can I Change the Order of Divs with CSS Based on Screen Size?. For more information, please follow other related articles on the PHP Chinese website!