CSS flex-direction:行列方向与键盘焦点顺序

CSS 的 flex-direction 用来设置 Flexbox 的主轴和项目排列方向。横排书写时,row 横向排列,column 纵向排列。请将它应用于设置了 display: flex 或 inline-flex 的父元素。

区分四种排列方向与两个轴

值 横排且从左向右书写时的布局
row 从左到右(默认)
row-reverse 从右到左
column 从上到下
column-reverse 从下到上

主轴是项目依次排列的方向,交叉轴与它垂直。justify-content 沿主轴对齐,align-items 沿交叉轴对齐。在横排书写中,从 row 切换为 column 后,justify-content: center 的居中效果也会从水平变为垂直。参见 CSS Flexbox · flex-direction 和 CSS Flexbox · Alignment。

用相同链接比较四种排列方式

将代码保存为 flex-direction.html 并打开。四个方框内都是按 A、B、C 顺序写入的链接,只有父元素的方向不同。初始设置为从左向右的 dir="ltr"。

<!doctype html>
<html lang="zh" dir="ltr">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>比较 Flex 的四种排列方向</title>
  <style>
    body { margin: 20px; font: 16px/1.6 system-ui, sans-serif; color: #203348; }
    * { box-sizing: border-box; }
    h1 { font-size: 24px; }
    h2 { margin: 14px 0 6px; font-size: 16px; }
    .samples { max-width: 560px; }
    .box { display: flex; gap: 8px; height: 132px; padding: 10px;
      border: 1px solid #88a4b6; background: #eef5f8; }
    .box a { display: grid; place-items: center; flex: none;
      width: 48px; height: 28px; color: white; background: #176b86;
      text-decoration: none; }
    .box a:focus-visible { outline: 3px solid #bc5b00; outline-offset: 2px; }
    .row { flex-direction: row; }
    .row-reverse { flex-direction: row-reverse; }
    .column { flex-direction: column; }
    .column-reverse { flex-direction: column-reverse; }
  </style>
</head>
<body>
<h1>比较 flex-direction 取值</h1>
<div class="samples">
<section><h2>row</h2>
<div class="box row">
  <a href="#result">A</a><a href="#result">B</a><a href="#result">C</a>
</div></section>
<section><h2>row-reverse</h2>
<div class="box row-reverse">
  <a href="#result">A</a><a href="#result">B</a><a href="#result">C</a>
</div></section>
<section><h2>column</h2>
<div class="box column">
  <a href="#result">A</a><a href="#result">B</a><a href="#result">C</a>
</div></section>
<section><h2>column-reverse</h2>
<div class="box column-reverse">
  <a href="#result">A</a><a href="#result">B</a><a href="#result">C</a>
</div></section>
</div>
<p id="result">每个方框中的 HTML 顺序都是 A → B → C。</p>
</body>
</html>

在 row 中,A 从左端开始,而在 row-reverse 中,A 从右端开始。column 中 A 在最上方,column-reverse 中 A 在最下方。将 HTML 属性改为 dir="rtl" 后,在横排书写中两种横向布局的起点互换,纵向布局的起点保持不变。对比后恢复 ltr。 当 writing-mode 为竖排模式时,row 会沿纵向行内轴排列。

按窗口宽度把工具栏切换为纵向排列

要让工具栏在窄屏上纵向排列,可以用媒体查询切换方向,并让高度随内容变化。只把第一个方框的 row 类替换为 toolbar,再将下列规则放到 style 的末尾。请保留提供 display: flex 的 box 类。

.toolbar {
  flex-direction: row;
  height: auto;
}
@media (max-width: 640px) {
  .toolbar {
    flex-direction: column;
  }
}

当视口宽度不超过 640px 时,链接纵向排列;更宽时排成一行。对比后删除新增规则并恢复 row。如果希望继续保持横向排列,只在空间不足时把项目换到下一行,请设置 flex-wrap。

比较视觉顺序与 Tab 顺序

按 Tab 进入第二个方框。从左到右能看到 C、B、A,但焦点先到右侧的 A,再移到 B 和 C。反向排列会改变可见布局。对表单字段或操作步骤等顺序敏感的内容,应在 HTML 中按正确顺序编排。参见 CSS Flexbox · Reordering and Accessibility。