纯CSS3实现div hover显示删除图标,文本类div悬停背景遮罩异常如何修复
解决方案
核心调整逻辑
- 新增CSS伪元素实现全容器背景遮罩,无需额外添加DOM节点
- 修正容器布局属性适配文本类容器的宽度表现
- 移除删除按钮上和绝对定位冲突的样式类,避免位置偏移
修正后CSS代码
.img-wrap { position: relative; /* 适配文本容器宽度,若需固定宽度可自行修改 */ display: block; padding: 8px; transition: all 0.15s ease-in; } /* 新增遮罩层 */ .img-wrap::before { content: ''; position: absolute; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.2); z-index: 4; opacity: 0; transition: opacity 0.15s ease-in; /* 避免遮罩阻挡内部元素点击 */ pointer-events: none; } .img-wrap .close { position: absolute; top: 8px; right: 8px; z-index: 5; transition: opacity 0.15s ease-in; padding: 6px 8px; font-weight: bold; cursor: pointer; opacity: 0; text-align: center; font-size: 16px; line-height: 1; border-radius: 50%; background-color: rgba(5, 0, 0, 0.75); } /* hover时同时触发遮罩和删除按钮显示 */ .img-wrap:hover::before { opacity: 1; } .img-wrap:hover .close { opacity: 1; z-index: 10; }
HTML调整说明
删除close标签上和绝对定位冲突的float-right、mr-2、mt-2类即可,修改后代码如下:
<div class="img-wrap"> <a href="" class="close red rounded-lg p-2" title="DELETE"><i class="fas fa-trash-alt fa-lg text-white"></i></a> <div class="media"> <i class="fal fa-file fa-4x icon-pdf d-flex mr-3"></i> <div class="media-body"> <h6 class="mt-0 mb-0 grey-text font-weight-bold">This is an existing File</h6> <div><small><b class="mr-2">File Name</b> <a href="" target="_blank">${filename}</a> </small> </div> </div> </div> </div>
效果说明
- hover时会同时显示全容器半透明遮罩和右上角删除按钮
- 遮罩不会阻挡内部文本、链接的正常点击操作
- 所有效果纯CSS实现,无需引入JavaScript
内容的提问来源于stack exchange,提问作者javaLearner
相关产品推荐
相关产品推荐

