Skip to content

Instantly share code, notes, and snippets.

@retorillo
Created November 25, 2015 07:38
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save retorillo/40647b9267ef2bbeefb5 to your computer and use it in GitHub Desktop.
Save retorillo/40647b9267ef2bbeefb5 to your computer and use it in GitHub Desktop.
CSSのpositionとz-indexの関係 (absoluteやfixedよりもstaticを手前に表示する)

CSSのpositionとz-indexの関係 (absoluteやfixedよりもstaticを手前に表示する)

positionの種類

CSSのpositionは、static, absolute, relative, fixedがあり、デフォルトではstaticです。

要素のZ軸上での重なりは必ずしも、z-indexの値や、HTMLで記述した順番通りではなく、 このpositionとも密接な関係があります。

positionとZ軸上の位置関係

まずz-indexを指定せず、positionだけを考えた場合、次の順番で重ねられて表示されます。

  1. positionがstaticな要素(HTMLで記述されている順番)
  2. positionがstaticではない要素(HTMLで記述されている順番)

absolute、relative、fixedなどstaticではない要素は、 デフォルトのstaticな要素よりも記述順番に関係なく 必ずZ軸上で手前に描画されるという点は重要です。

staticな要素にはz-indexが指定できない

そして問題となるのはpositionがstaticの要素にはz-indexの指定はできない点です。 W3Cの定義には次の通り、absolute, relative, fixed以外でz-indexは動作しないとあります。

Only works on positioned elements(position: absolute;, position: relative; or position: fixed;).

staticな要素にはz-indexが指定できない。そして、前項目のルールの通り、 staticでない子要素のほうが必ずZ軸上手前に表示されるという点も考えると、 staticな要素を手間に表示することは不可能なように思えます。

z-indexに負の値を指定すればstaticの要素よりも下に表示される

z-indexが負の値の場合の取り扱いを示す明確なドキュメントが見当たらないので、 ここからは検証済みでの内容ではありますが推測です。

staticな要素はz-indexが指定できないのではなく、常にauto(0)として処理されているようです。

そこで、 staticな要素を、そうでない要素よりも上に表示したい場合、 z-indexに負の値を指定することで実現できるようです。 (IE 11.11, MS Edge 25.1, Firefox 42.0, Chrome 46.0で確認済みです)

たとえば、以下のdiv2(赤)はdiv1(fixed,青)より上に表示されます。

<style type="text/css">
div {
	width: 100px;
	height: 100px;
}
.div1 {
	background: #00E;
	position: fixed;
	z-index: -1;
	left: 50px;
	top: 50px;
	width: 100px;
	height: 100px;
}
.div2 {
	background: #E00;
}
</style>
<div class="div1"></div>
<div class="div2"></div>

参考URL

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment