Home > Web Front-end > CSS Tutorial > How Can I Change the Order of Divs with CSS Based on Screen Size?

How Can I Change the Order of Divs with CSS Based on Screen Size?

Susan Sarandon
Release: 2025-01-04 11:41:34
Original
682 people have browsed it

How Can I Change the Order of Divs with CSS Based on Screen Size?

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:

  • Elements are initially displayed as a row.
  • When the screen width falls below a defined breakpoint, they transition to a column layout.
  • The order of elements is modified in the column layout to create the desired arrangement.

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>
Copy after login

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 }
}
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template