CSS Z INDEX

CSS Z INDEX

Z index é a propriedade que especifica a ordem da pilha de um elemento.

<!DOCTYPE html>

<html>

<head>

<style>

img {

  position: absolute;

  left: 0px;

  top: 0px;

  z-index: -1;

}

</style>

</head>

<body>

<h1>Este é um cabeçalho</h1>

<img src="img_tree.png">

<p>Como a imagem tem um índice z de -1, ela será colocada atrás do texto.</p>

</body>

</html>

EXEMPLO 02

<!DOCTYPE html>

<html>

<head>

<style>

.container {

  position: relative;

}

 

.black-box {

  position: relative;

  z-index: 1;

  border: 2px solid black;

  height: 100px;

  margin: 30px;

}

 

.gray-box {

  position: absolute;

  z-index: 3; /* gray box will be above both green and black box */

  background: lightgray;

  height: 60px; 

  width: 70%;

  left: 50px;

  top: 50px;

}

 

.green-box {

  position: absolute;

  z-index: 2; /* green box will be above black box */

  background: lightgreen;

  width: 35%;

  left: 270px;

  top: -15px;

  height: 100px;

}

</style>

</head>

<body>

<h1>Exemplo de índice Z</h1>

<p>Um elemento com ordem de pilha maior está sempre acima de um elemento com ordem de pilha inferior.</p>

<div class="container">

  <div class="black-box">Caixa preta (índice z: 1)</div>

  <div class="gray-box">Caixa cinza (z-index: 3)</div>

  <div class="green-box">Caixa verde (z-index: 2)</div>

</div>

</body>

</html>

Sem índice z

<!DOCTYPE html>

<html>

<head>

<style>

.container {

  position: relative;

}

 

.black-box {

  position: relative;

  border: 2px solid black;

  height: 100px;

  margin: 30px;

}

 

.gray-box {

  position: absolute;

  background: lightgray;

  height: 60px; 

  width: 70%;

  left: 50px;

  top: 50px;

}

 

.green-box {

  position: absolute;

  background: lightgreen;

  width: 35%;

  left: 270px;

  top: -15px;

  height: 100px;

}

</style>

</head>

<body>

<h1>Elementos sobrepostos</h1>

 

<p>Se dois elementos posicionados se sobrepõem sem um z-index especificado, o elemento definido por último no código HTML será mostrado no topo:</p>

 

<div class="container">

  <div class="black-box">Caixa preta</div>

  <div class="gray-box">caixa cinza</div>

  <div class="green-box">caixa verde</div>

</div>

</body>

</html>