CSS order
The CSS order
property is part of the CSS Flexbox layout module and is used to control the order in which flex items appear inside a flex container. It allows you to change the visual order of elements without affecting the source order in the HTML.
The order
property is applied to individual flex items and is used to determine the item’s order within the flex container. By default, all flex items have an order
value of 0, which means they appear in the order they are defined in the source HTML.
The syntax for the order
property is as follows:
flex-item {
order: <integer>;
}
flex-item
: Represents the HTML element or class that is a flex item inside a flex container.<integer>
: Specifies the order of the flex item. It is a positive or negative integer value.
Example:
HTML:
<div class="flex-container">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
</div>
CSS:
.flex-container {
display: flex;
}
.item {
padding: 10px;
border: 1px solid black;
}
.item:nth-child(1) {
order: 3;
}
.item:nth-child(2) {
order: 1;
}
.item:nth-child(3) {
order: 2;
}
In this example, we have a flex container with three flex items. By using the order
property, we change the visual order of the items. The first item (with content “1”) has an order of 3, the second item (with content “2”) has an order of 1, and the third item (with content “3”) has an order of 2. As a result, the items appear on the screen in the order 2, 3, 1, even though their original order in the HTML is 1, 2, 3.
The order
property is a powerful tool for controlling the visual layout of flex items, especially when you want to change their appearance without modifying the HTML structure. However, it’s essential to use it judiciously and avoid excessive use, as complex orderings can lead to confusing and hard-to-maintain code.
Keep in mind that the order
property only applies to flex items inside a flex container. It does not work on elements that are not part of a flex container.