Z-Index e JavaScript para Rollover
-
26-09-2019 - |
Pergunta
Eu tenho um contêiner (div) com uma imagem de fundo. Nesta div, há um menu - uma lista horizontal. O que eu preciso é inserir uma imagem no OnMouseOver, posicionando -a absolutamente e mostrando -a por trás do texto (é claro!) E além da imagem de fundo da div. Eu também uso o jQuery, mas acho que isso não importa. O problema pode ser visualizado online. Vamos para http://www.w3schools.com/css/tryit.asp?filename=trycss_zindex e cole o seguinte texto
<html> <head> <style type="text/css"> img { top: 0; left: 0; position:absolute; z-index:-1; } #main { color: red; margin: 30px; padding: 20px; width: 700px; min-height: 400px; z-index: -2; background-image: url("http://www.google.com/logos/mother10-hp.gif"); background-repeat: no-repeat; } </style> </head> <body> <div id="main"> <h1>Z-Index question:</h1> <img src="w3css.gif" width="100" height="140" /> <p>How can we place the green pic between the text and the div#main?</p> <p>I need the green gif to appear</p> <ol> <li>On top of #main's background image</li> <li>Behind the text</li> </ol> </div> </body> </html>
Solução
Parece que você precisa position:relative;
, absolute
ou fixed
em uma div para o z-index
para fazer efeito.
Outras dicas
Citando o w3c:
O Z-Index funciona apenas em elementos posicionados (
position:absolute
,position:relative
, ouposition:fixed
).
Eu fiz isso funcionei para o seu exemplo. Espero que ajude.
<html>
<head>
<style type="text/css">
.img1 {
top: 0;
left: 0;
position:absolute;
z-index:2;
}
#wrapper {
background-image: url("http://www.google.com/logos/mother10-hp.gif");
background-repeat: no-repeat;
z-index:1;
width:600px;
height:600px;
}
#main {
color: red;
margin: 30px;
padding: 20px;
width: 700px;
min-height: 400px;
z-index: 3;
position:absolute;
}
</style>
</head>
<body>
<div id="wrapper">
<div class="img1">
<img src="w3css.gif" width="100" height="140" />
</div>
<div id="main">
<h1>Z-Index question:</h1>
<p>How can we place the green pic between the text and the div#main?</p>
<p>I need the green gif to appear</p>
<ol>
<li>On top of #main's background image</li>
<li>Behind the text</li>
</ol>
</div>
</div>
</body>
</html>
Você só pode usar o Z-índice em elementos posicionados, aqui o invólucro não está posicionado, mas ele é imprensado entre os dois divs. Como eu disse, isso funciona para o exemplo publicado e não é 100% preciso, você precisará adicionar posicionamento para seus outros elementos em seu projeto. :)