LoginSignup
0
1

More than 3 years have passed since last update.

スタックコンテキストについて

Posted at

目的

  • z-index使用時に、重なり順が想定と違っていた
  • 重なりの仕組みについて整理する

スタックコンテキスト

  • スタック(stack)は積み上げる、コンテキスト(context)は文脈という意味
  • positionをstatic以外、かつz-indexを指定した場合に生成される集まりのとこ
  • z-indexを使用することで、同じスタックコンテキストの要素同士の重なり順を指定できる

実例

CSSとHTMLはこんな感じ(色や位置の記述は割愛)

<div class="squares">
  <div class="square square-red">z-index:2</div>
  <div class="square square-green">
    z-index:3
    <div class="square square-blue">z-index:1</div>
  </div>
</div>
.squares {
  position: relative;
}

.square {
  position: absolute;
  width: 10rem;
  height: 10rem;
}

.square--red {
  z-index: 2;
}

.square--blue {
  z-index: 1;
}

.square--green {
  z-index: 3;
}

スクリーンショット 2021-01-06 22.53.06.png

・z-indexが1の要素が、一番上に表示されている
・これは、z-indexが3の親要素が起点となっているから
・各要素の重なり順序は下表のようになっている

z-index スタックコンテキスト 重なり順
2 root root→赤(z-index:2)
1 緑(z-index:3)→青(z-index:1)
3 root root→緑(z-index:3)

青はz-index:3の緑を起点としているため、一番上に表示される

まとめ

z-indexを使用するときは、起点に注意しよう

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