2016-06-24 8 views
1

他の要素の中の最初の要素を対象にする必要がありますが、どういうわけか機能しません。対象:first-childまたは:nth-​​of-type(1)

サイドバーの最初のh2をターゲットにしたいだけです。

どうすればいいですか?

私はfirst-childnth-of-typeで試しましたが、動作しません。

#sidebar h2:first-child { 
 
    color: blue; 
 
}
<div id="sidebar"> 
 
    <div class="right"> 
 
    <div class="container-right"> 
 
     <div class="freetext"> 
 
     <h2>Heading - target me only</h2> 
 
     <p>Text</p> 
 
     </div> 
 
     <div class="freetext"> 
 
     <h2>Heading</h2> 
 
     <p>Text</p> 
 
     </div> 
 
    </div> 
 
    </div> 
 
</div>

ここfiddleを参照してください。

+0

_「と私はちょうどそのサイドバーの最初のH2をターゲットにしたいです。どうしたらいいですか? " - あなたはできません。最低でも_that_だけに基づいています。 nth-fooなどはすべて要素のDOM位置に基づいています。 – CBroe

答えて

1

first-child親のdivh2に設定する必要があります。

#sidebar > div > div > div:first-child > h2 { 
    color: blue; 
} 

または:

#sidebar div.freetext:first-child > h2 { 
    color: blue; 
} 

<div id="sidebar"> 
    <div class="right"> 
     <div class="container-right"> 
      <div class="freetext"> 
       <h2>heading - target me</h2> 
       <p>Text</p> 
      </div> 
      <div class="freetext"> 
       <h2>Heading</h2> 
       <p>Text</p> 
      </div> 
     </div> 
    </div> 
</div> 

jsFiddle here

+1

はい、これは問題ありません。ありがとう。 – Meek

2

これは仕事を行います。

#sidebar .freetext:first-child h2 { 
 
    color: blue; 
 
}
<div id="sidebar"> 
 
    <div class="right"> 
 
     <div class="container-right"> 
 
      <div class="freetext"> 
 
       <h2>Heading - target me only</h2> 
 
       <p>Text</p> 
 
      </div> 
 
      <div class="freetext"> 
 
       <h2>Heading</h2> 
 
       <p>Text</p> 
 
      </div> 
 
     </div> 
 
    </div> 
 
</div>

関連する問題