LoginSignup
3
1

More than 3 years have passed since last update.

【SASS・CSS】nth-of-typeを孫要素など配下の指定した要素のみに適用する簡単な方法

Last updated at Posted at 2021-04-09

nth-of-typeを使ってネストした深い要素にスタイルを適用する方法について。

ある深い要素にスタイルを適用するには、繰り返す親要素にnth-of-typeを適用し、その配下でタグを絞り込むと簡単に適用できる。

.css
繰り返す親要素のセレクタ:nth-of-type() 対象のセレクタ { 処理 }

セレクタを繋ぐスペースは配下の絞り込み。絞り込みは、直下を表す>や、且つを表す.も使える。

>(参考)cssセレクタの記号の意味

実例

次のようなul > li > div > div > p という深い階層の繰り返しがある場合に、nth-of-typeを使って、一番深いpタグのみにスタイルを適用する。

html
<ul>
  <li class="nth-test-li">
    liの要素
    <div class="nth-test-div1">
      li > div1の要素
      <div class="nth-test-div2">
        li > div1 > div2の要素
        <p class="nth-test-p">li > div1 > div2 > pの要素</p>
      </div>
    </div>
  </li>
  繰り返し
</ul>



繰り返す親要素はli class="nth-test-li"なので、これにnth-of-typeを適用する。

その次にスペースを開けてスタイルを適用したい要素を指定する。

.css
.nth-test-li:nth-of-type(2n) .nth-test-p {
  color: blue;
}

偶数番目のnth-test-liクラスの中のnth-test-pのある要素にのみスタイルを適用する指示になる。

image.png

狙ったタグのみがスタイル適用されている。


SASS(scss)を使うと簡単にかける。

scssを使うとわかりやすく記述できる。

.scss
.nth-test-li{
  &:nth-of-type(2n){
    .nth-test-p{
      color: blue;
    }
  }
}

↓↑同じ

.css
.nth-test-li:nth-of-type(2n) .nth-test-p {
  color: blue;
}

&は外側のセレクタを代入する。内側の階層で記号がない場合はスペースを空けてつなげる(配下の意味)。



以上。

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