LoginSignup
16

More than 5 years have passed since last update.

レイヤー管理には便利なsassのindex関数が便利

Posted at

横からでてくるパララックス?とか横スクロールメニューとか、
Webで「ちょっと」インタラクティブな表現をしようとすると、お世話になる「z-index」プロパティ。

「ちょっと」で済めばよいが、レイヤーが増えれば増えるほど、その度に管理してるレイヤーの「z-index」プロパティを値を一個一個書き換える必要がでてきて、結構大変。

この辺りのレイヤー管理をsassのindex関数使うと、うんと楽になるので、ご紹介。

sass の「Lists」

sassには「Lists」という配列みたいなデータ型があります。
このListsの宣言は、こんな感じ

scss
$list:item3, item2, item1;

これだけだと、イマイチ使いドコロが分かりづらいのですね。
実はこれ、sassに備わってるindex関数と組み合わせると結構便利なことができちゃうのです!

sass のindex関数

index関数は、その名のとおり、「Lists」内のindexを返してくれる関数です。

ex)

sassのindex関数で
css:scss
$list:item3, item2, item1;
index($list, item1)

とやると、$listの中に「item1」が何番目にいるかを返してくれます。
この例だと、「3」が帰ってきます。

「Lists」x index関数

1 レイヤー管理したい要素に任意の名前をつけて(クラス名と一緒にすると分かりやすいかも)、Listsを作ります。
css:scss
$list:item3, item2, item1;

2 次に、各要素のz-indexプロパティをindex関数で定義します。
```css:scss
$list:item3, item2, item1;

.item1 {
...
z-index: index($list, item1);
}
.item2 {
...
z-index: index($list, item2);
}
.item3 {
...
z-index: index($list, item3);
}
```
これをcssにするとこうなります。

scss
.item1 {
  ...
  z-index: 3;
}
.item2 {
  ...
  z-index: 2;
}
.item3 {
  ...
  z-index: 1;
}

こうすれば、レイヤーが増えても、各要素のz-indexプロパティを変えることなく、$list内にレイヤーを追加するだけでokなので便利です

デモ

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
16