LoginSignup
15
10

More than 5 years have passed since last update.

nth-of-typeとnth-childをSassで書く

Last updated at Posted at 2017-12-23

nth-of-typeとnth-childをscssファイルで書こうと思ったら詰まったので、備忘録として記しておきます。

やりたかった事

以下のようなhtml構造のときに、2番目のProject__main__iconにだけマージンを当てたい。

<div class="Project__main">
  <div class="Project__main__icon">
    <img src="/assets/img/hoge.svg" alt="">
  </div>
  <div class="Project__main__icon"> //←これにマージンを当てたい
    <img src="/assets/img/fuga.svg" alt="">
  </div>
  <div class="Project__main__icon">
    <img src="/assets/img/piyo.svg" alt="">
  </div>
</div>

(先に)成功例

結論としてどうすれば上手く行ったかを載せておきます。:nth-of-type(2)用に1段階ネストを深くしないと当たらないんですね。

.Project {
  &__main {
    &__icon {
      &:nth-of-type(2){
        margin: 0 60px;
      }
    }
  }
}

失敗例

下記が上手くといくと思った書き方です。cssファイルでの書き方的に以下で良いと勘違いしてしまいました。

.Project {
  &__main {
    &__icon:nth-of-type(2) {
      margin: 0 60px;
    }
  }
}

同じようなことで困る人に記事が届きますように!

参考

15
10
3

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