HTMLのテーブルに外枠のみを表示する方法
HTMLのテーブルに外枠のみを表示する方法について説明します。
外枠だけを表示し、内部のセル間に境界線を表示しないためには、CSSを用いてテーブルのスタイルを設定します。
以下にその方法を示すためのHTMLとCSSのサンプルコードを提供します。
HTMLファイル (index.html)
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>テーブルの外枠のみ表示</title> <link rel="stylesheet" href="styles.css"> </head> <body> <table class="test-table"> <thead> <tr> <th class="test-header">ヘッダー1</th> <th class="test-header">ヘッダー2</th> </tr> </thead> <tbody> <tr> <td class="test-cell">データ1</td> <td class="test-cell">データ2</td> </tr> <tr> <td class="test-cell">データ3</td> <td class="test-cell">データ4</td> </tr> </tbody> </table> </body> </html>
CSSファイル (styles.css)
.test-table { border-collapse: collapse; width: 100%; } .test-table, .test-table th, .test-table td { border: 1px solid black; } .test-table th, .test-table td { padding: 8px; text-align: left; } .test-table th { background-color: #f2f2f2; } .test-table td { background-color: #ffffff; }
説明
1. HTMLファイル:
テーブルの基本構造を定義します。
class="test-table"でテーブル全体にスタイルを適用し、class="test-header"とclass="test-cell"でヘッダーとデータセルにスタイルを適用します。
2. CSSファイル:
- .test-tableクラスでテーブルの全体スタイルを指定します。
border-collapse: collapse;を使用して、テーブルセルの境界線を重ね合わせて表示します。
- .test-table, .test-table th, .test-table tdでテーブル、ヘッダー、データセルに1pxの黒い境界線を設定します。
- .test-table th, .test-table tdでセルに8pxのパディングを設定し、テキストを左寄せにします。
- .test-table thでヘッダーセルの背景色を設定し、.test-table tdでデータセルの背景色を設定します。
この方法で、テーブルの外枠だけを表示し、内部のセル間には境界線を表示しないように設定できます。