LoginSignup
136
137

More than 5 years have passed since last update.

Sassを使ったz-indexの管理

Last updated at Posted at 2016-05-16

Sass(SCSS)を使ったz-indexの管理には、Sassy Z-Index Management For Complex Layouts – Smashing Magazine を使っていた。

$z: header, nav, pulldown, child;

.header {
  z-index: index($z, header); // 1
}
.child {
  z-index: index($z, child); // 4
}

ただ変数にリストを突っ込んでいくと、数が多くなった時に可読性が悪く、つらい。

$z: header, nav, pulldown, child, hoge, hoge, hoge, hoge, ...;

可読性を上げて管理

カッコで囲むことで可読性が良くなり、z-indexの上下関係がわかりやすくなる。

$z-map: (
  header, 
  nav,
  pulldown, 
  child
);

下記のようなz関数のようなものを用意して使えば、z-indexの管理が楽になると思う。

$z-map: (
  header, 
  nav,
  pulldown, 
  child
);

// z-index
@function z($name) {
  @return index($z-map, $name);
}
// @debug z(header); // 1

.header {
  z-index: z(header); // 1
}
.child {
  z-index: z(child); // 4
}

追記 2016-05-18

この状態だとスタック文脈の問題もあるので、改良した。
第2階層まで対応。

$z-map: (
  header: true,
  nav: true,
  child: (
    foo,
    bar
  )
);

// z-index
@function z($name, $childname: 0) {
  $getkey: map-get($z-map, $name);
  @if $childname != 0 {
    @return index($getkey, $childname);
  }
  @return inspect(index($z-map, ($name $getkey) ));
}

.header {
  z-index: z(header); // 1
}

.child {
  z-index: z(child); // 3
}

.child-foo {
  z-index: z(child, bar); // 2
}

libsass対応

@function z($name, $childname: 0) {
  $getkey: map-get($z-map, $name);
  $counter: 1;
  $is-index: 0;
  @if $childname != 0 {
    @return index($getkey, $childname);
  }

  @each $map-key, $map-value in $z-map {
    @if $map-key == $name {
      $is-index: $counter;
    }
    $counter: $counter + 1;
  }

  @return $is-index;
}

追記: 2017-03-28

スタック文脈による第2階層以上に対応。
ついでに逆順指定もできるようにした。
MixinsとFunctions集にまとめたので、そのまま使っても、抜き出して使っても可。
そのまま使う場合は、coreディレクトリの中を、任意のSassディレクトリに移動して使う。

kojika17/fawn

$z-map: (
  header: true,
  nav: true,
  child: (
    foo: true,
    bar: (
     hoge: true,
     fuga: true,
     hohoho: true
    )
  )
);

@import 'fawn'; // $z-mapの後に読み込む

.header {
  z-index: z(header); // 1
}
.child {
  z-index: z(child); // 3
}
.child-foo {
  z-index: z(child, bar, hohoho); // 3
}

逆順にしたいときは、$z-map-reverse変数の値をtrueにする。

$z-map: (
  header: true,
  nav: true,
  child: (
    foo: true,
    bar: (
     hoge: true,
     fuga: true,
     hohoho: true
    )
  )
);
$z-map-reverse: true;
@import 'fawn'; // $z-mapと$z-map-reverseの後に読み込む

.header {
  z-index: z(header); // 3
}
.child {
  z-index: z(child); // 1
}
.child-foo {
  z-index: z(child, bar, hohoho); // 1
}
136
137
2

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
136
137