CSS table-layout: fixedで表の列幅を指定する

後続の行の内容に左右されない列幅にするには、table-layout: fixedとwidthを指定します。既定のautoはセルの内容も幅の計算に使います。固定レイアウトでは、長い値を折り返すか省略記号で表示するかを別に設定します。

幅を指定しても表が広がる理由

自動レイアウトでは、空白のない文、大きな画像、white-space: nowrapなどがセルの最小幅を広げ、width: 500pxを超えることがあります。固定レイアウトでは、まず<col>の幅、次に先頭行のセルの幅を使い、残りを幅の未指定の列に分配します。列や境界線、間隔にさらに幅が必要なら、表も広がる場合があります。 CSS 2.2 · Automatic table layout CSS 2.2 · Fixed table layout

同じデータでautoとfixedを比べる

コードをtable-layout.htmlとして保存し、ブラウザーで開きます。2つの表は同じファイル名とwidth: 500pxを持ちます。最初の表はファイル名を1行で収めるために広がります。2つ目は先頭列に120pxを割り当て、残りを次の列に使い、長い名前を省略記号で示します。

<!doctype html>
<html lang="ja">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>表と列の幅を比較する</title>
  <style>
    body { margin: 20px; font: 16px/1.6 system-ui, sans-serif; color: #203348; }
    .jb-table-scroll { overflow-x: auto; margin-bottom: 24px; }
    table { width: 500px; border-collapse: collapse; }
    th, td { border: 1px solid #8a9bad; padding: 8px; text-align: left; }
    th { background: #edf3fa; }
    .filename { font-family: monospace; }
    .auto .filename { white-space: nowrap; }
    .fixed { table-layout: fixed; }
    .fixed th:first-child { width: 120px; }
    .fixed .filename {
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  </style>
</head>
<body>
<h1>表の幅と長い値</h1>
<div class="jb-table-scroll" tabindex="0" role="region" aria-labelledby="auto-caption">
  <table class="jb-table-01 auto">
    <caption id="auto-caption">auto:内容に合わせて広がる</caption>
    <thead><tr><th scope="col">種類</th><th scope="col">ファイル名</th></tr></thead>
    <tbody><tr><td>文書</td><td class="filename">quarterly-report-for-the-international-development-team-with-regional-appendices-and-budget-tables-2024.pdf</td></tr></tbody>
  </table>
</div>
<div class="jb-table-scroll" tabindex="0" role="region" aria-labelledby="fixed-caption">
  <table class="jb-table-01 fixed">
    <caption id="fixed-caption">fixed:500pxの中に配置</caption>
    <thead><tr><th scope="col">種類</th><th scope="col">ファイル名</th></tr></thead>
    <tbody><tr><td>文書</td><td class="filename">quarterly-report-for-the-international-development-team-with-regional-appendices-and-budget-tables-2024.pdf</td></tr></tbody>
  </table>
</div>
</body>
</html>

開発者ツールで2つのtableの幅を比較します。2つ目でtext-overflowだけを無効にすると、省略記号が消えても文字は途中で切れたままです。狭いウィンドウではTabでスクロール領域にフォーカスし、矢印キーで横へ移動できます。

長いセルを折り返すか省略する

ファイル名を最後まで表示するには、2つ目の表のファイル名セルのルールを下のCSSで置き換えます。white-space: normalが改行を許可し、overflow-wrap: anywhereが空白のない値を折り返します。列幅は維持され、行が高くなることがあります。

.fixed .filename {
  white-space: normal;
  overflow-wrap: anywhere;
}

省略記号はwhite-space: nowrap、overflow: hidden、text-overflow: ellipsisの組み合わせです。切り詰めた値をすべて読む必要がある場合は、展開や詳細表示の手段を用意します。 CSS Overflow · text-overflow

列幅と表全体の幅を調整する

先頭列を120pxから160pxに広げると、同じ500pxの表で2列目が狭くなります。比較後は120pxに戻します。複数列の幅を指定するには、<colgroup>内に<col>を置きます。

表を親の幅に合わせるにはwidth: 100%を使えます。親が狭いと、先頭列の120pxが残りの列を圧迫します。先頭列を割合で指定するか、数字や日付を1行で表示したい場合は最小幅とスクロール領域を併用します。