CSS3 セレクター :first-of-type とクラス名? 質問する

CSS3 セレクター :first-of-type とクラス名? 質問する

CSS3 セレクターを使用して、特定のクラス名を持つ最初の要素を選択することは可能ですか:first-of-type? テストが成功しなかったため、不可能だと思います。

コード (http://jsfiddle.net/YWY4L/):

p:first-of-type {color:blue}
p.myclass1:first-of-type {color:red}
.myclass2:first-of-type {color:green}
<div>
  <div>This text should appear as normal</div>
  <p>This text should be blue.</p>
  <p class="myclass1">This text should appear red.</p>
  <p class="myclass2">This text should appear green.</p>
</div>

ベストアンサー1

いいえ、セレクターを 1 つだけ使用しても不可能です。:first-of-type疑似クラスは、そのタイプ( divpなど) の最初の要素を選択します。その疑似クラスでクラス セレクター (またはタイプ セレクター) を使用すると、要素が指定されたクラス (または指定されたタイプ) を持ち兄弟の中でそのタイプの最初の要素である場合に、その要素を選択することになります。

:first-of-class残念ながら、CSS では、クラスの最初の出現のみを選択するセレクターは提供されていません。回避策として、次のようなものを使用できます。

.myclass1 { color: red; }
.myclass1 ~ .myclass1 { color: /* default, or inherited from parent div */; }

回避策の説明と図解が示されていますここそしてここ

おすすめ記事