HTMLのテーブルにフォームを組み込む方法
HTMLテーブルにフォームを組み込む方法について説明します。
以下では、HTMLとCSSを別ファイルに分けて、クラス名やID名には test- プレフィックスを使用します。
HTMLファイル (index.html)
まず、基本的な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">名前</th> <th class="test-header">メール</th> <th class="test-header">コメント</th> <th class="test-header">アクション</th> </tr> </thead> <tbody> <tr> <td class="test-cell"> <input type="text" class="test-input" name="name" placeholder="名前を入力"> </td> <td class="test-cell"> <input type="email" class="test-input" name="email" placeholder="メールアドレスを入力"> </td> <td class="test-cell"> <textarea class="test-textarea" name="comment" placeholder="コメントを入力"></textarea> </td> <td class="test-cell"> <button class="test-button" type="submit">送信</button> </td> </tr> <!-- 他の行も必要に応じて追加できます --> </tbody> </table> </body> </html>
CSSファイル (styles.css)
次に、HTMLファイルで使用されるクラスにスタイルを追加します。
これにより、テーブルとフォーム要素が適切に表示されます。
.test-table { width: 100%; border-collapse: collapse; } .test-header, .test-cell { border: 1px solid #ddd; padding: 8px; text-align: left; } .test-header { background-color: #f4f4f4; font-weight: bold; } .test-input, .test-textarea { width: 100%; padding: 8px; box-sizing: border-box; } .test-button { background-color: #4CAF50; color: white; border: none; padding: 10px 20px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; margin: 4px 2px; cursor: pointer; } .test-button:hover { background-color: #45a049; } .test-textarea { height: 100px; }
説明
1. HTMLファイルの構造:
index.htmlファイルでは、table要素を使用してテーブルを作成し、その中にフォーム要素を含めています。
theadセクションにはテーブルのヘッダーを、tbodyセクションにはテーブルの内容を含めています。
各行にinputやtextareaなどのフォーム要素を追加しています。
これにより、ユーザーがデータを入力できるようになります。
2. CSSファイルのスタイル:
styles.cssファイルでは、テーブルのスタイルを設定し、フォーム要素の見た目を整えています。
test-tableクラスでテーブルの幅を設定し、test-headerおよびtest-cellクラスでセルのスタイルを指定しています。
test-inputやtest-textareaクラスでフォーム要素のサイズやパディングを調整し、test-buttonクラスでボタンのスタイルを設定しています。
この構造により、HTMLテーブル内にフォームを組み込み、視覚的に整ったレイアウトを実現することができます。
必要に応じて、テーブルの行を追加したり、フォーム要素の種類を変更したりすることで、さらにカスタマイズできます。