Cuando los elementos son posicionados, pueden superponerse con otros elementos. La propiedad z-index especifica el orden de pila de un elemento (qué elemento debe colocarse delante o detrás de los demás). Un elemento puede tener un orden de pila positivo o negativo.
Ejm
<!DOCTYPE html> <html> <head> <style> img { position: absolute; left: 0px; top: 0px; z-index: -1; } </style> </head> <body> <h1>This is a heading</h1> <img src="img_tree.png"> <p>Como la imagen tiene un z-index:-1; se pondrá detrás del texto</p> </body> </html>
Nota: z-index solo funciona en elementos posicionados (position: absolute, position: relative, position: fixed o position: sticky) y elementos flexibles (elementos que son hijos directos de visualización: elementos flexibles).
Ejm
<!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>Z-index Example</h1> <p>An element with greater stack order is always above an element with a lower stack order.</p> <div class="container"> <div class="black-box">Black box (z-index: 1)</div> <div class="gray-box">Gray box (z-index: 3)</div> <div class="green-box">Green box (z-index: 2)</div> </div> </body> </html>
Sin z-index
Si dos elementos posicionados se superponen sin especificar un z-index, el último elemento definido en el código HTML se mostrará en la parte superior.