You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CSS中#hey元素:hover悬停效果失效,求原因及解决方法

问题:#hey元素的:hover颜色切换效果不生效

我是CSS新手,自主练习时遇到问题:鼠标悬停在#hey元素上时,文字颜色应变为红色,但该:hover效果完全没有生效。以下是编写的代码,希望知晓问题原因与解决办法。

代码示例

CSS代码

body {
  font-family: "Open Sans", sans-serif;
  height: 3000px;
  margin: 0;
}

h1 {
  text-align: center;
}

#container {
  background-color: #003049;
  width: 90%;
  height: 500px;
  margin: 0 auto;
  border: 5px solid #003049;
  position: relative;
}

.header {
  position: fixed;
  display: flex;
  width: 90%;
  height: 500px;
}

.header div {
  width: 100%;
  height: 100%;
  transition: all 0.2s;
}

.header div:nth-of-type(1):hover {
  background-color: transparent !important;
}

.header div:nth-of-type(2):hover {
  background-color: transparent !important;
}

.header div:nth-of-type(3):hover {
  background-color: transparent !important;
}

.header div:nth-of-type(4):hover {
  background-color: transparent !important;
}

.header div:nth-of-type(5):hover {
  background-color: transparent !important;
}

#hey {
  color: white;
  font-family: "Open Sans", sans-serif;
  font-size: 3em;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

#hey:hover {
  color: red;
}

HTML代码

<h1>Trying something page</h1>

<section id="container">
  <div id="hey">HEY</div>
  <div class="header">
    <div style="background-color: #80ffdb"></div>
    <div style="background-color: #64dfdf"></div>
    <div style="background-color: #48bfe3"></div>
    <div style="background-color: #5390d9"></div>
    <div style="background-color: #6930c3"></div>
  </div>
</section>

问题原因

核心问题是元素层级覆盖:.header设置了position: fixed,在CSS层叠上下文规则中,固定定位元素的默认层级高于绝对定位的#hey,相当于.header的彩色div层完全覆盖在#hey文字上方。此时鼠标悬停时,实际触发的是上层.header div的hover事件,根本碰不到下方的#hey,所以文字变色效果不生效。

解决办法

方案1:提升#hey的层级

给#hey添加z-index属性,让它的层级高于.header:

#hey {
  color: white;
  font-family: "Open Sans", sans-serif;
  font-size: 3em;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 10; /* 新增:设置足够大的z-index值 */
}

方案2:让.header不拦截鼠标事件

如果不需要.header区域响应鼠标操作,可以给它添加pointer-events: none,让鼠标事件直接穿透到下方的#hey:

.header {
  position: fixed;
  display: flex;
  width: 90%;
  height: 500px;
  pointer-events: none; /* 新增:禁止元素拦截鼠标事件 */
}

如果仍需要.header内的div能响应hover,可单独给这些div恢复鼠标事件:

.header div {
  width: 100%;
  height: 100%;
  transition: all 0.2s;
  pointer-events: auto; /* 针对div恢复鼠标事件 */
}

内容的提问来源于stack exchange,提问作者İsmail Berberoğlu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 17:17:26