0
1

htmlで表の上を固定

Posted at

HTMLとCSSを使用して、表の上2行だけを固定し、残りの行を上下にスクロールできるようにする方法を以下に示します。

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>固定ヘッダーテーブル</title>
    <style>
        .table-container {
            height: 300px; /* 表全体の高さを指定 */
            overflow-y: auto; /* 垂直スクロールを有効にする */
            border: 1px solid #ddd;
        }

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

        th, td {
            padding: 8px 16px;
            border: 1px solid #ddd;
            text-align: left;
        }

        thead {
            position: sticky;
            top: 0;
            background-color: #f9f9f9;
        }

        /* 2行目も固定 */
        thead tr:nth-child(2) {
            position: sticky;
            top: 40px; /* 行の高さを指定 */
            background-color: #f1f1f1;
        }
    </style>
</head>
<body>
    <div class="table-container">
        <table>
            <thead>
                <tr>
                    <th>ヘッダー1</th>
                    <th>ヘッダー2</th>
                    <th>ヘッダー3</th>
                </tr>
                <tr>
                    <th>サブヘッダー1</th>
                    <th>サブヘッダー2</th>
                    <th>サブヘッダー3</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>データ1</td>
                    <td>データ2</td>
                    <td>データ3</td>
                </tr>
                <tr>
                    <td>データ4</td>
                    <td>データ5</td>
                    <td>データ6</td>
                </tr>
                <tr>
                    <td>データ7</td>
                    <td>データ8</td>
                    <td>データ9</td>
                </tr>
                <!-- さらにデータ行を追加 -->
            </tbody>
        </table>
    </div>
</body>
</html>

このコードでは、CSSの position: sticky; を使用して、表の上2行を固定しています。また、 table-container クラスに overflow-y: auto; を設定して、垂直スクロールを有効にしています。表の高さ(ここでは300px)は必要に応じて調整してください。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1