要素の描画順・表示順を指定する - Z-indexによる要素の表示順の指定 - CSS

CSSで要素の描画順・表示順を指定するコードを紹介します。

z-indexを指定しない場合

sample00.css

.box01{
  background-color:#6dc448;
  width:128px;
  height:128px;
  position:absolute;
  left:32px;
  top:32px;
}

.box02{
  background-color:#4e8dc3;
  width:128px;
  height:128px;
  position:absolute;
  left:64px;
  top:64px;

}

.box03{
  background-color:#d35353;
  width:128px;
  height:128px;
  position:absolute;
  left:48px;
  top:96px;

}

sample00.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
  <link rel="stylesheet" type="text/css" href="sample00.css" />
</head>
<body>
  <div class="box01">box01</div>
  <div class="box02">box02</div>
  <div class="box03">box03</div>
</body>
</html>

表示結果

HTMLファイルを表示すると下図の結果となります。HTMLファイルで記述した順番に描画されていることがわかります。

z-indexを指定

sample01.css

.box01{
  background-color:#6dc448;
  width:128px;
  height:128px;
  position:absolute;
  left:32px;
  top:32px;
  z-index:0;
}

.box02{
  background-color:#4e8dc3;
  width:128px;
  height:128px;
  position:absolute;
  left:64px;
  top:64px;
  z-index:2;
}

.box03{
  background-color:#d35353;
  width:128px;
  height:128px;
  position:absolute;
  left:48px;
  top:96px;
  z-index:1;
}

sample01.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
  <link rel="stylesheet" type="text/css" href="sample01.css" />
</head>
<body>
  <div class="box01">box01</div>
  <div class="box02">box02</div>
  <div class="box03">box03</div>
</body>
</html>

表示結果

HTMLファイルを表示すると下図の結果となります。z-indexの数値の大きいものほど手前に描画されています。


著者
iPentecのメインデザイナー
Webページ、Webクリエイティブのデザインを担当。PhotoshopやIllustratorの作業もする。
掲載日: 2013-12-11
iPentec all rights reserverd.