Bootstrapテーブルの使い方
見やすい表を簡単に作成
Bootstrapのテーブルクラスを使えば、ストライプ、ホバー、ボーダーなどのスタイルをクラスひとつで適用できます。
レスポンシブ対応のテーブルも簡単に作れます。
こんな人向けの記事です
- HTMLテーブルの見た目をすぐに改善したい
- Bootstrapのテーブルクラスを知りたい
- スマホでもテーブルを見やすく表示したい
Step 1基本のテーブル
table クラスを付けるだけで、パディングとボーダーが整ったテーブルになります。
| # | 名前 | メール |
|---|---|---|
| 1 | 田中太郎 | tanaka@example.com |
| 2 | 鈴木花子 | suzuki@example.com |
| 3 | 佐藤一郎 | sato@example.com |
HTML
<table class="table">
<thead>
<tr>
<th>#</th>
<th>名前</th>
<th>メール</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>田中太郎</td>
<td>tanaka@example.com</td>
</tr>
<tr>
<td>2</td>
<td>鈴木花子</td>
<td>suzuki@example.com</td>
</tr>
<tr>
<td>3</td>
<td>佐藤一郎</td>
<td>sato@example.com</td>
</tr>
</tbody>
</table>
Step 2ストライプとホバー
| クラス | 効果 |
|---|---|
table-striped | 奇数行にストライプ(縞模様) |
table-hover | 行にホバーすると背景色が変わる |
table-bordered | 全セルにボーダーを追加 |
table-borderless | ボーダーを全て除去 |
table-sm | パディングを半分にしてコンパクトに |
HTML
<!-- ストライプ + ホバー + ボーダー -->
<table class="table table-striped table-hover table-bordered">
...
</table>
<!-- コンパクトなテーブル -->
<table class="table table-sm">
...
</table>
複数のクラスを組み合わせ可能
table-striped、table-hover、table-bordered は自由に組み合わせて使えます。
Step 3テーブルの色バリエーション
HTML
<!-- テーブル全体の色 -->
<table class="table table-dark">...</table>
<table class="table table-dark table-striped">...</table>
<!-- ヘッダーだけ暗く -->
<table class="table">
<thead class="table-dark">...</thead>
<tbody>...</tbody>
</table>
<!-- ヘッダーを薄いグレーに -->
<thead class="table-light">...</thead>
Step 4レスポンシブテーブル
テーブルを table-responsive で囲むと、横幅が画面に収まらない時に横スクロールが出ます。
HTML
<!-- 常にレスポンシブ -->
<div class="table-responsive">
<table class="table">...</table>
</div>
<!-- 特定の画面幅以下でのみレスポンシブ -->
<div class="table-responsive-md">
<table class="table">...</table>
</div>
table-responsive は table の親要素に付ける
table-responsive は <table> 自体ではなく、<div> で囲んでその <div> に付けます。
Step 5行や列の色付け
HTML
<!-- 特定の行に色を付ける -->
<tr class="table-success">...</tr>
<tr class="table-danger">...</tr>
<tr class="table-warning">...</tr>
<!-- 特定のセルに色を付ける -->
<td class="table-primary">重要</td>
まとめ
tableクラスで基本スタイルを適用table-striped/table-hover/table-borderedで見た目を調整table-darkでダークテーマtable-responsiveで横スクロール対応(親divに付ける)table-success等で行やセルを個別に色付け