悬停效果不适用于z索引较低的元素



我对z索引有问题。我在这个jsfiddle中模拟了我的问题。我在一个容器中有两个兄弟div。其中一个充当容器的背景,并在其元素上具有悬停效果,因此当您将鼠标悬停在其元素时,元素的颜色会发生变化。为了把它放在第二个div后面,我使用了一个负的z索引,但悬停效果对它不起作用。这个问题有什么解决方案吗?我看到了一些关于这个主题的问题,但没有任何有效的答案。。。

提前谢谢。

<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>

查看我对CSS所做的编辑。如果将背景为灰绿色的div1设置为z-index: 0;(元素的默认层(,并将z-index: 1;用于div2,使其位于默认层之上的第一层,效果会更好。请参见下文。

* {
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>

在代码中,您将鼠标悬停在容器div上,而不是div1上。

Z指数是指建筑物的标高,你可以从观鸟的角度来观察它。

要解决这个问题,您应该将div1/div2设置为正z索引,并更改div2相对于父div的位置。

获取有关div定位的更多信息:

https://tomelliott.com/html-css/css-position-child-div-parent

编辑:这里有一个快速的例子来模拟你想要的悬停效果。

<!DOCTYPE html>
<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;
}
.grandparent {
width: 250px;
height: 250px;
background-color: lightgreen;
position: relative;
}
.parent {
width: 150px;
height: 150px;
/*position:absolute;*/
bottom: 0px;
}
.child {
width: 70px;
height: 70px;
background-color: rgb(245, 189, 116);
position: absolute;
right: 0px;
top: 0px;
}
.parent p:hover {
color: red;
}
.child p:hover {
color: red;
}
</style>
</head>
<body>
<div class="grandparent">
<div class="parent">
<p>div 1 does work now</p>
<div class="child"><p>div 2 works</p></div>
</div>
</div>
</body>
</html>

最新更新