CSSでnot(:first-child)の書き方

CSSでnot(:first-child)の書き方

CSSでnot(:first-child)を使用することで、特定の要素を除外してスタイルを適用することができます。
not()は、CSSのセレクタの一部であり、指定されたセレクタにマッチしない要素を選択するために使われます。
具体的には、:not(:first-child)という記述を使用することで、親要素の最初の子要素以外のすべての子要素にスタイルを適用することができます。

以下は、not(:first-child)を使用して、最初の子要素を除外してスタイルを適用する例です。

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>not(:first-child) の例</title>
  <link rel="stylesheet" href="styles.css">
</head>
<body>
  <ul class="test-list">
    <li class="test-item">アイテム 1</li>
    <li class="test-item">アイテム 2</li>
    <li class="test-item">アイテム 3</li>
    <li class="test-item">アイテム 4</li>
  </ul>
</body>
</html>
CSS (styles.css)
.test-list {
  list-style-type: none;
  padding: 0;
}

.test-item {
  padding: 10px;
  background-color: #f0f0f0;
  border: 1px solid #ccc;
}

.test-item:not(:first-child) {
  background-color: #d0d0d0; /* 最初の子以外の背景色を変更 */
}

説明

  • test-list クラスを持つ ul 要素は、リストアイテムがリストスタイルなしで表示されるようにします。
  • test-item クラスを持つ li 要素は、全体に共通のスタイル(パディング、背景色、ボーダー)を適用します。
  • test-item:not(:first-child) セレクタは、最初の li 要素を除いたすべての li 要素に対して、背景色を変更するスタイルを適用します。

このようにして、not(:first-child)を使うことで、特定の要素にだけスタイルを適用し、他の要素には異なるスタイルを適用することができます。