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;
}解释
.mouse-active-show-element { display: none; }:- 这段CSS选择器选择了所有带有类名
mouse-active-show-element的元素。 display: none;表示这些元素默认情况下不会显示在页面上。它们会被完全隐藏,既不占据空间也不可见。
- 这段CSS选择器选择了所有带有类名
.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元素会以行内元素的形式显示出来。
- 这段CSS选择器选择了当鼠标悬停在带有类名
这样就实现了只有当鼠标悬停在特定父元素上时,对应的子元素才会显示的效果。
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>