鼠标悬停父元素时仅模糊自身,子元素保持清晰的CSS实现
解决方案
问题根源:当你给父元素.item添加filter: blur()时,这个滤镜会作用于整个元素及其所有子元素,无法通过给子元素设置filter: none来抵消——滤镜是对元素整体的处理,不是可继承的样式属性。
正确的做法是把需要模糊的内容和不受影响的子元素分离:将.item内需要模糊的部分(图片、描述文本等)包裹在一个独立容器中,hover时仅对这个容器应用模糊效果,而不是整个.item。
修改后的代码
HTML
<div class="item"> <!-- 新增容器包裹需要模糊的内容 --> <div class="item-content"> <img src="your-image-url" alt="项目图片"> <p>这里是项目描述文本,会在hover时被模糊</p> </div> <p id="codeCheck3" class="codeCheck"> <a href="#">Code</a> </p> </div>
CSS
#projectDiv { display: flex; flex-flow: row wrap; justify-content: space-evenly; align-items: flex-start; margin-top: 30px; width: 100%; height: fit-content; } .item { z-index: 0; margin-top: 30px; position: relative; /* 新增,确保绝对定位的.codeCheck相对于.item定位 */ display: flex; flex-direction: column; justify-content: flex-start; align-items: center; height: 400px; width: 250px; border: 5px solid blue; background-color: #ea342300; } /* 新增容器样式,承接原.item内内容的布局 */ .item-content { display: flex; flex-direction: column; justify-content: flex-start; align-items: center; width: 100%; height: 100%; } .item-content img { margin: 0; width: 100%; height: 200px; background-size: cover; } .item-content p { color: blue; font-size: 14px; font-family: 'kabeteh'; font-weight: bolder; margin: 0; padding: 10px; text-align: justify; display: flex; flex-direction: column; justify-content: center; } .codeCheck { position: absolute; left: 170px; visibility: hidden; display: none; background-color: white; transition: transform .5s ease; } .codeCheck a { padding: 5px; background-color: white; text-orientation: upright; writing-mode: vertical-lr; text-decoration: none; font-family: 'secondFont'; } .item:hover { z-index: 0; box-shadow: 1px 1px 20px 0px blue; /* 移除原有的filter: blur(3px) */ } /* hover时仅模糊内容容器 */ .item:hover .item-content { filter: blur(3px); } .item:hover .codeCheck { z-index: 9; transform: translateY(10%); display: block; visibility: visible; }
关键改动说明
- 新增
.item-content容器,将需要模糊的内容移入其中,和.codeCheck同级 - 给
.item添加position: relative,确保绝对定位的.codeCheck始终相对于父元素定位 - 将原
.item:hover中的filter: blur()移到.item:hover .item-content上,仅模糊内容区域 - 调整原
.item img、.item p的选择器为.item-content img、.item-content p,保证样式继承
内容的提问来源于stack exchange,提问作者nexus-4
相关产品推荐
相关产品推荐

