There are many scenarios where one would want to change the order of elements in a container using CSS, but I find I use the CSS order property the most when I want to change the order of elements stacked on the smaller resolutions.
So this is how the issue might occur. We have a few elements laid out one next to the other on desktop and large-screen devices.
However, when we change the resolution or open our layout on the small screen, the elements would stack in the order they are added in the code (be it HTML, JSX, or whatever). And here lies our problem.
Even though everything is displaying correctly, the order of the columns is wrong. We want it to follow a natural flow, in this case, “text-image followed by text-image”. We can easily fix this with a line or two of CSS using the CSS order property.
HOW TO USE CSS ORDER PROPERTY
CSS order property specifies the visual order of the elements in a container, which are by default lined up as in our source code.
One thing to note is that the order property will work only for containers that are displayed as grid or flex.
So, what I might do in the example above is to display the container (div, section..) as grid (or flex):
.container { display: grid; }
and then change the order of my elements by adding a class (for example, .order-2) to the element I want to change, and on which resolution (in my case, on mobile phones, below the width of 480px):
@media screen and (max-width: 480px) { .order-2 { order: 2; } }
And we’re good to go.
Leave a comment