4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

:nth-of-type()をクラスに対して指定した時の挙動

Posted at

めっちゃ特殊な動きをします。
例えば.content:nth-of-type(2)という指定をした場合、
containerというクラスを持った要素と同じ階層にある要素を全て洗い出し、もし2番目の要素がcontainerというクラスを持っていたらスタイルを適用する
という動きをします。

何を言ってるかわからないと思うので、以下に例を挙げます。

例1

html
<div>
  クラスなし
</div>
<div class="container">
  1つ目のcontainer
</div>
<div class="container">
  2つ目のcontainer
</div>
css
.container:nth-of-type(2){
  background: yellow;
}

出力

同階層の2番目の要素がcontainerクラスなのでスタイルが適用されます。
 2019-11-26 20.06.31.png

例2

html
<div>
  クラスなし
</div>
<div class="container">
  1つ目のcontainer
</div>
<div class="container">
  2つ目のcontainer
</div>
css
/*  odd = 奇数 */
.container:nth-of-type(odd){
  background: yellow;
}

出力

同階層の奇数番目の要素のうち、containerクラスを持つのは3番目だけです。
 2019-11-26 20.09.39.png

例3

html
<p>同階層のP要素</p>
<div>
  クラスなし
</div>
<ul>
  <li>同階層のリストの子要素</li>
  <li>同階層のリストの子要素</li>
</ul>
<div class="container">
  1つ目のcontainer
</div>
<div class="container">
  2つ目のcontainer
</div>
css
.container:nth-child(5){
  background: yellow;
}

出力

同階層の5番目の要素がcontainerクラスを持つので、スタイルが適用されます。
 2019-11-26 20.17.42.png

まとめ

変な動きをするので気をつけて!

4
1
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
4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?