【CSS】display: tableを使ってテーブルを作成する方法

HTMLのdivタグを使用してCSSで表を作成する方法について解説します。

HTML

HTMLの基本的な構造を定義します。divタグを使用して、テーブル、行、セルを表現します。

<div class="table">
  <div class="row">
    <div class="cell">Row 1, Cell 1</div>
    <div class="cell">Row 1, Cell 2</div>
  </div>
  <div class="row">
    <div class="cell">Row 2, Cell 1</div>
    <div class="cell">Row 2, Cell 2</div>
  </div>
</div>

CSS

CSSを設定して、divタグが表のように見えるようにします。

.table {
  display: table;
  width: 100%;
  border-collapse: collapse;
}

.row {
  display: table-row;
}

.cell {
  display: table-cell;
  padding: 10px;
  border: 1px solid #000;
}

/* ヘッダー用のスタイル(必要に応じて) */
.header {
  background-color: #f2f2f2;
  font-weight: bold;
}

完成したコード

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Table Example</title>
<style>
  .table {
    display: table;
    width: 100%;
    border-collapse: collapse;
  }

  .row {
    display: table-row;
  }

  .cell {
    display: table-cell;
    padding: 10px;
    border: 1px solid #000;
  }

  .header {
    background-color: #f2f2f2;
    font-weight: bold;
  }
</style>
</head>
<body>

<div class="table">
  <div class="row header">
    <div class="cell">Header 1</div>
    <div class="cell">Header 2</div>
  </div>
  <div class="row">
    <div class="cell">Row 1, Cell 1</div>
    <div class="cell">Row 1, Cell 2</div>
  </div>
  <div class="row">
    <div class="cell">Row 2, Cell 1</div>
    <div class="cell">Row 2, Cell 2</div>
  </div>
</div>

</body>
</html>
Header 1
Header 2
Row 1, Cell 1
Row 1, Cell 2
Row 2, Cell 1
Row 2, Cell 2
  • .tableクラスで全体をテーブルレイアウトに設定します。
  • .rowクラスで各行を定義します。
  • .cellクラスで各セルを定義します。
  • .headerクラスは、ヘッダー行のスタイルを設定するために使用されます(オプション)。

必要に応じて、スタイルや構造をカスタマイズして、より複雑な表を作成することも可能です。