0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【フロントエンド1000本ノック】0033_構造疑似クラス(:first-child, :last-child, :nth-child(n))を使い、テーブルの奇数行と偶数行で背景色を変えるスタイル(zebra striping)を実装せよ。

Posted at

この記事は人間が書きました

はじめに

こんにちは、赤神です!
この記事は、「1000本ノック」という取り組みの中のフロントエンドのための課題の1つです。

「1000本ノックとは」
https://qiita.com/sora_akagami/items/c8da4296dea3823376ca

構造擬似クラスとは?

構造擬似クラスは、要素が兄弟要素の中で「何番目にいるか」という構造上の位置に基づいてスタイルを適用します。

  • :first-child:兄弟の中で最初の要素
  • :last-child:兄弟の中で最後の要素
  • nth-child(n):兄弟の中でn番目の要素

nth-childn には、数字だけでなく特別なキーワードも使えます。

  • :nth-child(odd):奇数番目の要素を選択(1, 3, 5, ...)
  • :nth-child(even):偶数番目の要素を選択(2, 4, 6, ...)

これを使うことで、HTML に class を追加しなくても、交互にスタイルを変えるシマウマ模様が簡単に実装できます。

作成したコード

index.html
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>フロントエンド1000本ノック 0033</title>
    <style>
      tbody tr:nth-child(odd) {
        background-color: lightgray;
      }
      tbody tr:nth-child(even) {
        background-color: white;
      }
    </style>
</head>
<body>
    <main>
      <h1>構造擬似クラス</h1>

      <table border="1">
        <thead>
          <tr>
            <th>商品名</th>
            <th>価格 (円)</th>
            <th>在庫数</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td>りんご</td>
            <td>150</td>
            <td>50</td>
          </tr>
          <tr>
            <td>バナナ</td>
            <td>100</td>
            <td>80</td>
          </tr>
          <tr>
            <td>オレンジ</td>
            <td>120</td>
            <td>35</td>
          </tr>
          <tr>
            <td>ぶどう</td>
            <td>200</td>
            <td>60</td>
          </tr>
          <tr>
            <td>いちご</td>
            <td>180</td>
            <td>45</td>
          </tr>
        </tbody>
        <tfoot>
          <tr>
            <td colspan="2">合計アイテム数</td>
            <td>5</td>
          </tr>
        </tfoot>
      </table>
    </main>
    <footer>
      <p>Copyright 2025</p>
      <p>フロントエンド1000本ノック</p>
    </footer>

</body>
</html>
0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?