Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> CSS

Giá trị row-reverse của flex-direction trong CSS

Giá trị row-reverse của flex-direction xếp các flex items theo hàng ngang từ phải sang trái (ngược với row mặc định). Trục chính vẫn là ngang nhưng hướng đảo ngược.

Ví dụ: flex-direction: row-reverse

<!DOCTYPE html>
<html>
<head>
  <style>
    .mycontainer {
      display: flex;
      flex-direction: row-reverse;
      background-color: #e67e22;
      padding: 10px;
      gap: 10px;
    }
    .mycontainer > div {
      background-color: white;
      text-align: center;
      line-height: 40px;
      font-size: 25px;
      width: 100px;
      border-radius: 4px;
    }
  </style>
</head>
<body>
  <h1>Quiz</h1>
  <div class="mycontainer">
    <div>Q1</div>
    <div>Q2</div>
    <div>Q3</div>
    <div>Q4</div>
    <div>Q5</div>
    <div>Q6</div>
  </div>
</body>
</html>

Kết quả hiển thị

Thứ tự DOM: Q1, Q2, Q3, Q4, Q5, Q6

Thứ tự VISUAL: Q6, Q5, Q4, Q3, Q2, Q1 (từ trái sang phải)

So sánh row vs row-reverse

Thuộc tínhrow (mặc định)row-reverse
Hướng xếpTrái → PhảiPhải → Trái
Main axis startLeftRight
Main axis endRightLeft
justify-content: flex-startCăn tráiCăn phải
justify-content: flex-endCăn phảiCăn trái
Cross axisDọc (top→bottom)Dọc (top→bottom) - KHÔNG đổi

Ứng dụng thực tế

/ * RTL (Right-to-Left) languages: Arabic, Hebrew * /
[dir="rtl"] .nav {
  flex-direction: row-reverse;
}

/* Hoặc dùng logical properties (hiện đại) */
.nav {
  display: flex;
  /* Không cần row-reverse, dùng margin-inline */
}
.logo { margin-inline-end: auto; } /* Tự động sang phải trong RTL */

/* Visual reordering không thay đổi DOM order */
.chat-messages {
  display: flex;
  flex-direction: column-reverse; /* Tin mới nhất ở dưới */
}

Lưu ý Accessibility

  • row-reverse chỉ thay đổi thứ tự visual, không thay DOM order
  • Tab navigation, screen reader vẫn theo thứ tự HTML
  • Chỉ dùng cho decorative reordering, không cho content logic
  • Cho RTL: ưu tiên dir="rtl" + logical properties thay vì row-reverse

Shorthand flex-flow

.container {
  flex-flow: row-reverse wrap; /* direction + wrap */
}