HTMLのテーブル内にdivタグを組み込む方法
HTMLのテーブル内に div タグを組み込む方法について、具体的な例を使って説明します。
以下のコード例では、テーブルのセル内に div タグを配置し、CSSでスタイリングする方法を示します。
HTMLとCSSは別々のファイルに分けて記載し、クラス名やID名には test- プレフィックスを使用します。
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>テーブル内のdivタグ</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"> <div class="test-div">セル 1</div> </td> <td class="test-cell"> <div class="test-div">セル 2</div> </td> </tr> <tr> <td class="test-cell"> <div class="test-div">セル 3</div> </td> <td class="test-cell"> <div class="test-div">セル 4</div> </td> </tr> </tbody> </table> </body> </html>
CSS (styles.css)
.test-table { width: 100%; border-collapse: collapse; } .test-header { background-color: #f4f4f4; border: 1px solid #ddd; padding: 10px; text-align: left; } .test-cell { border: 1px solid #ddd; padding: 10px; } .test-div { background-color: #e0e0e0; padding: 20px; border-radius: 5px; text-align: center; }
説明
この例では、テーブルの tbody セクション内の各セルに div タグを配置しています。
div タグは、テーブルのセル内にコンテンツを持たせるために使用されます。
CSSファイルでは、テーブル、ヘッダー、セル、そして div タグに対してスタイルを定義しています。
- .test-table クラスは、テーブル全体のスタイルを設定します。
border-collapse プロパティにより、セルの境界線が重ならないようにしています。
- .test-header クラスは、テーブルヘッダーのスタイルを設定しています。
背景色、境界線、パディング、テキストの配置などを指定しています。
- .test-cell クラスは、テーブルのセルにスタイルを適用します。
セルの境界線とパディングを設定しています。
- .test-div クラスは、セル内の div タグのスタイルを設定しています。
背景色、パディング、境界線の角を丸くするスタイル、テキストの中央揃えを指定しています。
この構造により、テーブル内の各セルに div タグを埋め込むことができ、div タグのスタイルを調整することで、セル内のコンテンツの見た目をカスタマイズできます。