47
48

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

CSS でテーブルに行番号を振る

Last updated at Posted at 2017-02-21

リスト要素に対して番号を振りたければ list-style-type: decimal を使えば良いんですが、テーブルだとそうもいかないです。しかし行番号を振るためだけに JavaScript は使いたくない。

そういうときは CSS Counters を使います。

html
<table>
  <thead>
    <tr>
      <th></th>
      <th>column1</th>
      <th>column2</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td></td>
      <td>foo</td>
      <td></td>
    </tr>
    <tr>
      <td></td>
      <td>bar</td>
      <td></td>
    </tr>
    <tr>
      <td></td>
      <td>baz</td>
      <td></td>
    </tr>
  </tbody>
</table>
css
table {
  counter-reset: rowCount;
}

table > tbody > tr {
  counter-increment: rowCount;
}

table > tbody > tr > td:first-child::before {
  content: counter(rowCount);
}

こう書くと、

こうなります。

CSS Counters は CSS 2.1 の仕様1のためほぼすべてのブラウザで動作する2ので、覚えておくと便利です。

  1. https://developer.mozilla.org/ja/docs/Web/Guide/CSS/Counters

  2. http://caniuse.com/#feat=css-counters

47
48
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
47
48

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?