CSS `order` Property: Controlling Item Display Order in Flexbox and Grid Layouts
Learn how to use the CSS `order` property to control the visual arrangement of items within flex and grid containers. This tutorial explains how to rearrange items using integer values, demonstrating how to override source order for creating flexible and customized layouts without modifying the HTML structure.
Controlling Item Order with CSS `order`
Understanding the `order` Property
The CSS `order` property controls the visual order of items within a flex container or grid container. It allows you to rearrange items without changing their position in the source code. The order is determined by assigning integer values to the `order` property for each item. Items with lower `order` values appear earlier in the layout; higher values appear later. This only affects visual display; it does not change the document's source order or the tab order.
`order` Property Syntax and Values
The syntax is:
order:
The values are:
: An integer value specifying the item's order. Lower values appear earlier. The default value is 0. Negative values are allowed.initial
: Resets the property to its default value (0).inherit
: Inherits the value from the parent element.
Examples of Using `order`
These examples show how to control the order of items within a flex container. You would need the corresponding HTML (likely a `div` with `display: flex;`) and CSS to see the effects in a browser. The `order` property is applied to each of the items (the child elements) within the flex container.
Example 1: Using Negative and Duplicate Values
This example illustrates the impact of both negative order values and the situation where multiple elements have the same `order` value. Note how elements with lower values appear earlier, and elements with the same values are ordered according to their appearance in the HTML source code.
Example CSS
.flex-container {
display: flex;
}
.item-1 { order: -2; }
.item-2 { order: -1; }
.item-3 { order: 0; }
.item-4 { order: 0; } /* Same order as item-3; will appear after item-3 */
.item-5 { order: 1; }
.item-6 { order: 2; }
.item-7 { order: 3; }
.item-8 { order: 4; }
Example 2: Simple Ordering
This simpler example demonstrates basic ordering using positive integer values.
Example CSS
.flex-container {
display: flex;
}
.item-1 { order: 3; }
.item-2 { order: 1; }
.item-3 { order: 2; }
.item-4 { order: 4; }
.item-5 { order: 0; }
Conclusion
The `order` property provides a flexible and intuitive way to control the visual arrangement of items within flexbox and grid layouts. By assigning integer values, you can rearrange elements without modifying the HTML source order, improving design flexibility and simplifying the creation of custom layouts.