I have a problem with the z-index. I have simulated my problem in this jsfiddle . I have two siblings div inside a container. one of them works as a background of the container and has a hover effect on its elements so when you hover on its elements , the color of the elements changes. to place it behinde the second div I used a negative z-index , but the hover effect doesn't work on it. any solutions to this proplem? I have seen some questions about this subject but without any valid answer...
Thanks in advance.
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
* {
margin: 0px;
padding: 0px;
box-sizing: border-box;
text-decoration: none;
font-family: "Gill Sans", "Gill Sans MT", Calibri, "Trebuchet MS", sans-serif;
}
.container {
width: 1000px;
height: 600px;
position: relative;
}
.div1 {
position: absolute;
z-index: -10;
top: 0;
left: 0;
bottom: 0;
right: 0;
background-color: lightgreen;
}
.div2 {
width: 200px;
height: 200px;
background-color: rgb(245, 189, 116);
margin: 0 auto;
}
.div1 p:hover {
color: red;
}
.div2 p:hover {
color: red;
}
</style>
</head>
<body>
<div class="container">
<div class="div1"><p>div 1 doesn't work</p></div>
<div class="div2"><p>div 2 works</p></div>
</div>
</body>
</html>
See the edits I made to your CSS. It will work better if you set div1
with the background limegreen as z-index: 0;
which is the default layer for elements and use z-index: 1;
for div2
so it's on the first layer above the default one. See below.
* {
margin: 0px;
padding: 0px;
box-sizing: border-box;
text-decoration: none;
font-family: "Gill Sans", "Gill Sans MT", Calibri, "Trebuchet MS", sans-serif;
}
.container {
width: 1000px;
height: 600px;
position: relative;
}
.div1 {
position: absolute;
z-index: 0;
top:0;
left: 0;
bottom: 0;
right: 0;
background-color: lightgreen;
}
.div2 {
position: relative;
width: 200px;
height: 200px;
background-color: rgb(245, 189, 116);
margin: 0 auto;
z-index: 1;
}
.div1 > p:hover{
color: red;
}
.div2 > p:hover{
color: red;
}
<div class="container">
<div class="div1"><p>div 1 works now</p></div>
<div class="div2"><p>div 2 works</p></div>
</div>