Skip to content

css伪类实现鼠标悬停父元素时子元素才显示

实现了只有当鼠标悬停在特定父元素上时,对应的子元素才会显示的效果。

css代码

css
.mouse-active-show-container:hover .mouse-active-show-element {
    display: inline;
}

.mouse-active-show-element {
    display: none;
}
scss
.mouse-active-show-container {
   &:hover .mouse-active-show-element {
      display: inline;
   }
}

.mouse-active-show-element {
   display: none;
}

解释

  1. .mouse-active-show-element { display: none; }:

    • 这段CSS选择器选择了所有带有类名 mouse-active-show-element 的元素。
    • display: none; 表示这些元素默认情况下不会显示在页面上。它们会被完全隐藏,既不占据空间也不可见。
  2. .mouse-active-show-container:hover .mouse-active-show-element { display: inline; }:

    • 这段CSS选择器选择了当鼠标悬停在带有类名 mouse-active-show-container 的元素上时,其内部的所有带有类名 mouse-active-show-element 的子元素。
    • :hover 是一个伪类,表示当用户将鼠标指针移动到指定的元素上时应用的样式。
    • display: inline; 表示当鼠标悬停在 .mouse-active-show-container 上时,.mouse-active-show-element 元素会以行内元素的形式显示出来。

这样就实现了只有当鼠标悬停在特定父元素上时,对应的子元素才会显示的效果。

html示例

html
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>Hover Effect</title>
    <style>

        .item {
            display: flex;
            align-items: center;
            gap: 100px;
            border: 1px solid red;
        }

        .mouse-active-show-container:hover .mouse-active-show-element {
            display: inline;
        }

        .mouse-active-show-element {
            display: none;
        }
    </style>
</head>
<body>
<div class="item mouse-active-show-container">
    <h1>a</h1>
    <span class="mouse-active-show-element">
            a1
        </span>
</div>

<div class="item mouse-active-show-container">
    <h1>b</h1>
    <span class="mouse-active-show-element">
            b1
        </span>
</div>
</body>
</html>
/src/technology/dateblog/2025/05/20250521-css%E4%BC%AA%E7%B1%BB%E5%AE%9E%E7%8E%B0%E9%BC%A0%E6%A0%87%E6%82%AC%E5%81%9C%E7%88%B6%E5%85%83%E7%B4%A0%E6%97%B6%E5%AD%90%E5%85%83%E7%B4%A0%E6%89%8D%E6%98%BE%E7%A4%BA.html