如何仅用CSS实现hover一个类时修改同类其他元素样式?
实现悬停单个
.right元素时修改其余同类元素样式 问题背景
你有多个带.right类的div元素,需要实现:鼠标悬停任意一个.right元素时,为其余所有.right元素应用指定样式,且只能修改CSS文件、无法改动HTML结构。
解决方案
由于CSS没有直接的"反向兄弟选择器",可以通过容器hover + 排除当前hover元素的思路实现:当父容器#container被hover时,给所有.right元素设置样式,再用:not(:hover)排除掉当前正被鼠标悬停的那个.right元素,从而达到目标效果。
修改后的完整代码
CSS代码
body { margin: 0; } #container { position: relative; background-color: #d5d8dc; margin-top: 100px; margin-left: 100px; width: 400px; height: 400px; } .right { background-color: #2ecc71; position: absolute; width: 320px; height: 40px; /* 可选:添加过渡让样式变化更平滑 */ transition: all 0.3s ease; } .right:nth-child(1) { left: 20%; } .right:nth-child(2) { transform: rotate(90deg); right: -140px; top: 140px; } .right:nth-child(3) { left: 20%; bottom: 20%; } .right:nth-child(4) { transform: rotate(90deg); right: +140px; top: 140px; z-index: 2; } .left { background-color: #e74c3c; position: absolute; width: 320px; height: 40px; } .left:nth-child(5) { left: 0; top: 20%; } .left:nth-child(6) { transform: rotate(90deg); right: -60px; top: 220px; } .left:nth-child(7) { left: 0; bottom: 0; } .left:nth-child(8) { transform: rotate(90deg); left: -140px; top: 220px; } .left:hover { z-index: 3; } .right:hover { z-index: 3; } /* 核心样式:悬停容器时,所有未被hover的.right元素应用指定样式 */ #container:hover .right:not(:hover) { /* 这里替换成你需要的样式,示例为变暗+半透明 */ background-color: #27ae60; opacity: 0.7; }
HTML代码
<div id="container"> <div class="right"></div> <div class="right"></div> <div class="right"></div> <div class="right"></div> <div class="left"></div> <div class="left"></div> <div class="left"></div> <div class="left"></div> </div>
关键说明
- 核心逻辑是
#container:hover .right:not(:hover):当鼠标进入容器范围(即悬停任意一个.right元素时),选中所有未被hover的.right元素,为其应用自定义样式。 - 你可以将
#container:hover .right:not(:hover)内的样式替换为需求中的指定效果(比如调整缩放、边框、阴影等)。 - 额外添加的
transition属性用于让样式变化更流畅,可根据需求保留或移除。
内容的提问来源于stack exchange,提问作者Ehsan
相关产品推荐
相关产品推荐

