LoginSignup
19
15

More than 5 years have passed since last update.

first-childセレクタとfirst-of-typeセレクタの違い

Posted at

first-childが何故か効かない、ということがあったので少し調べました。

first-childセレクタ

以下のCSSが適用されるか調べてみる。

.sample p:first-child {
    font-weight: bold;
}

CSSが適用される場合


<div class="sample">
    <p>how</p>
    <h2>are</h2>
    <h2>you</h2>
    <p>gone?</p>
</div>

この場合は、一番初めのp要素にcssが適用される。

CSSが適用されない場合


<div class="sample">
    <h2>are</h2>
    <p>how</p>
    <h2>you</h2>
    <p>gone?</p>
</div>

この場合、pにはCSSが適用されない。
sampleの初めの子要素(first-child)がh2要素だからである。

p:first-childは、あくまでも「最初の子要素がp要素だった場合のみ」装飾が適用される。

first-of-typeセレクタ

p要素だけカウントしてCSSを適用したい場合は、以下のように書く。

.sample p:first-of-type {
    font-weight: bold;
}

last-childとlast-of-typeについても、
最後の子要素についてみるという以外は同じ考え方になります。

19
15
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
19
15