CSS :first-child と :last-child — 端の要素の選択
兄弟の中で最初と最後の要素をターゲットするCSS :first-childと:last-child疑似クラスを学びます。ボーダー、マージンの除去やエッジケースの処理に不可欠です。
Pseudo-classes
詳細な説明
CSS :first-child と :last-child
これらの疑似クラスは、親要素の最初または最後の子としての位置に基づいて要素をターゲットします。
構文
li:first-child {
border-top: none;
}
li:last-child {
border-bottom: none;
}
一般的なパターン
末尾のセパレーターの除去:
.breadcrumb li:last-child::after {
content: none;
}
端のマージンの除去:
.grid > *:first-child { margin-top: 0; }
.grid > *:last-child { margin-bottom: 0; }
関連する疑似クラス
| セレクター | マッチ |
|---|---|
:first-child |
親の最初の子 |
:last-child |
親の最後の子 |
:first-of-type |
そのタグタイプの最初 |
:last-of-type |
そのタグタイプの最後 |
:only-child |
兄弟のない要素 |
ユースケース
:first-childと:last-child疑似クラスは、リスト、グリッド、ナビゲーションのエッジケース処理に不可欠です。開発者は上部/下部のボーダーの除去、最初/最後のアイテムのマージンとパディングの調整、導入段落への特別なスタイリング、パンくずリストのセパレーター文字の処理、二重ボーダーのないクリーンなカードレイアウトの作成に使用します。