Thuộc tính order cho phép thay đổi thứ tự hiển thị của flex items mà không cần đổi HTML. Mặc định order: 0.
Ví dụ mã nguồn
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
.container {
height: 150px;
display: flex;
width: 100%;
border: 2px solid red;
gap: 10px;
}
div {
width: 200px;
height: 150px;
color: white;
text-align: center;
font-size: 30px;
display: flex;
align-items: center;
justify-content: center;
}
.first { background-color: rgb(55, 0, 255); order: 2; } /* Hiển thị thứ 2 */
.second { background-color: red; order: 3; } /* Hiển thị thứ 3 */
.third { background-color: rgb(140, 0, 255); order: 1; } /* Hiển thị thứ 1 */
</style>
</head>
<body>
<h1>Reordering Flex Items với order</h1>
<div class="container">
<div class="first">First Div (HTML thứ 1)</div>
<div class="second">Second Div (HTML thứ 2)</div>
<div class="third">Third Div (HTML thứ 3)</div>
</div>
<p>Thứ tự hiển thị: Third (1) → First (2) → Second (3)</p>
</body>
</html>
Cách hoạt động
- Items sắp xếp theo
ordertăng dần (âm → 0 → dương) - Cùng
orderthì theo thứ tự HTML (source order) - Không ảnh hưởng DOM, chỉ ảnh hưởng visual order
Ứng dụng thực tế
- Responsive reorder: Sidebar lên trên content trên mobile (
@media (max-width: 768px) { .sidebar { order: -1; } }) - Featured item: Đẩy item nổi bật lên đầu
- RTL support: Đảo thứ tự cho ngôn ngữ RTL
- Masonry-like: Kết hợp order nth-child cho layout đặc biệt
Cảnh báo Accessibility
order chỉ thay đổi visual order, không thay đổi tab order / screen reader order. Nếu thay đổi thứ tự quan trọng về mặt logic, hãy đổi HTML thay vì dùng CSS order.
/* Responsive reorder example */
@media (max-width: 768px) {
.header { order: 1; }
.main { order: 3; }
.sidebar { order: 2; }
.footer { order: 4; }
}