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

鼠标悬停外层div时显示内部元素的实现疑问

问题原因及解决方法

你的第二个嵌套示例失效,核心是CSS选择器使用错误:

  • 你写的.dtl-image:hover + .img-hover是相邻兄弟选择器,仅能匹配和.dtl-image同级且紧挨着的.img-hover元素。
  • 嵌套结构中,.img-hover是.dtl-image的子元素,需要用后代选择器才能选中。

修正步骤

  1. 修改CSS选择器,将.dtl-image:hover + .img-hover替换为.dtl-image:hover .img-hover
  2. 若要让按钮显示在背景图上方,可给外层.dtl-image设置position: relative,内部按钮设置position: absolute来定位(可选,根据需求调整位置)

修正后的完整代码

<!DOCTYPE html>
<html>
<head>
<style>
.dtl-image {
  border:1px solid #000;
  min-height:300px;
  background: center / contain no-repeat url("https://inventivewebdesign.com/wp-content/uploads/IWD-Logo-w-text-2016_600x425.png");
  position: relative; /* 为内部绝对定位元素提供参照 */
}

.img-hover {
  display: none;
  position: absolute;
  top: 20px;
  left: 20px;
  padding: 8px 16px;
  background: #fff;
  border: 1px solid #ccc;
}
    
/* 后代选择器:匹配.dtl-image内部的.img-hover */
.dtl-image:hover .img-hover {
  display: block;
}
</style>
</head>
<body>

<h2>Display an Element Below Image on Hover </h2>

<div class="dtl-image"></div>
<div class="img-hover">I am shown when someone hovers over the div above.</div>

<h2>Display an Inside Element Below Image on Hover</h2>

<div class="dtl-image">
  <div class="img-hover">I am shown when someone hovers over the outer div.</div>
</div>

</body>
</html>

额外说明

  • 后代选择器(空格分隔)会匹配所有嵌套层级的子元素,若只想匹配直接子元素,可改用子选择器.dtl-image:hover > .img-hover
  • 绝对定位的按钮可通过top/left/right/bottom属性调整到背景图的任意位置

内容的提问来源于stack exchange,提问作者Inventive Web Design

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 11:07:39