LoginSignup
20
13

More than 5 years have passed since last update.

Sassを使ってnth-childを省略して書く方法

Last updated at Posted at 2019-02-18

実現したいこと

画像をコンテナの右上に少しずつずらして表示したい
各画像に icon:nth-child(1) icon:nth-child(2) ... と書くのはシンプルじゃない。

スクリーンショット 2019-02-19 0.02.41.png

まずはVue.jsで画像を表示

index.vue
<template>
  <section class="fruit">
    <div class="fruit__container">
      <img
        v-for="(item, i) in items"
        :key="`fruit__container-key-${i}`"
        :src="item.url"
        :alt="item.title"
        class="fruit__container__icon"
      >
      本文
    </div>
  </section>
</template>

<script>
export default {
  data() {
    return {
      items: [
        { title: "apple", url: "https://placehold.jp/150x150.png" },
        { title: "banana", url: "https://placehold.jp/150x150.png" },
        { title: "orange", url: "https://placehold.jp/150x150.png" },
        { title: "peach", url: "https://placehold.jp/150x150.png" },
        { title: "grape", url: "https://placehold.jp/150x150.png" }
      ]
    };
  }
};
</script>

Sassを書いていく

style.scss
.fruit {
  background-color: #afeeee;
  padding: 50px 0;
  color: #fff;

  &__container {
    background-color: #fff;
    position: relative;
    width: 50%;
    margin: 0 auto;
    padding: 20px;
    border-radius: 15px;

    &__icon {
      position: absolute;
      top: -15px;
      width: 32px;
      height: 32px;
      margin-right: 5px;
      border: 1px solid #fff;
      border-radius: 50%;
    }
  }
}

この状態では各画像が重なっており1つしか見えていません。
各画像に対して nth-child を使って右にずらしてあげましょう。

スクリーンショット 2019-02-19 0.14.53.png

nth-childとfor文で画像をずらす

style.scss
.fruit {
  &__container {
    &__icon {
      //(略)
    }

    // アイコンを右からpositionsの位置に配置
    $positions: (5, 25, 44, 65, 85);

    @for $index from 1 through length($positions) {
      &__icon:nth-child(#{$index}) {
        right: #{nth($positions, $index)}px;
      }
    }
  }
}

$positions で各画像の位置を書きます。
for文の意味は日本語に直してあげるとわかりやすいです。

  • @for $index ($indexを繰り返す)
  • from 1 through (1から)
  • length($positions) ($positionsのlengthだけ)

なので、 @for の中では $index が1, 2, 3, ...と繰り返されています。
それを利用して nth-child に指定してあげます。

例えば、$index2 のときは。。

このように変換されます!
&__icon:nth-child(#{$index})&__icon:nth-child(2)
right: #{nth($positions, $index)}px;right: 25px;

変数をセレクタやプロパティ名にしたいときは #{} で囲います。
nth($n) はSassの関数で、指定した数($n)の要素を取り出すことができます。

まとめ

Sassの関数を使うことで可読性が下がるという意見も聞きますが、
今回のように細かい微修正は for文で書いた方がシンプルになり個人的には好きです!

20
13
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
20
13