html - 仅悬停覆盖图像上的 Bootstrap 4 卡
问题描述
我正在使用 Bootstrap 4 卡。当我将鼠标悬停在卡片的任何区域上时,透明覆盖层会覆盖整个卡片。我想要的效果是叠加层仅出现在顶部图像区域,而不是整个卡片。
HTML:
<div class="m-4">
<div class="card" style="width: 18rem;">
<img class="card-img-top" src="https://via.placeholder.com/150x100" alt="Card image cap">
<div class="card-overlay"></div>
<div class="card-body">
<h5 class="card-title">Card title</h5>
<p class="card-text">Some quick example text.</p>
</div>
</div>
</div>
CSS
.card-overlay {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
height: 100%;
width: 100%;
opacity: 0;
transition: .5s ease;
background: rgba(0, 0, 0, 0.5);
}
.card:hover .card-overlay {
opacity: 1;
}
解决方案
问题是您的所有元素都在同一个容器中。“card-overlay” div 填充了“card” div 的空间,因此它会影响其中的所有元素。我通过制作一个额外的容器来保存图像和图像叠加层解决了这个问题。
我已经像这样更改了您的代码:
HTML
<div class="m-4">
<div class="card" style="width: 18rem;">
<!-- A div to hold img and img-overlay -->
<div class="card-image">
<img class="card-img-top" src="https://via.placeholder.com/150x100" alt="Card image cap">
<div class="image-overlay"></div>
</div>
<!-- -->
<div class="card-body">
<h5 class="card-title">Card title</h5>
<p class="card-text">Some quick example text.</p>
</div>
</div>
</div>
CSS
/* Changing img holder position, so the overlay will be related to it */
.card-image {
position: relative;
}
.image-overlay {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
height: 100%;
width: 100%;
opacity: 0;
transition: .5s ease;
background: rgba(0, 0, 0, 0.5);
}
.card:hover .image-overlay {
opacity: 1;
}
推荐阅读
- python - 去除多列的基线
- ansible - Ansible 使用 lineinfile 包含带有变量问题的单引号
- java - Selenium4:“类型 WebDriver.TargetLocator 的方法 newWindow(WindowType) 未定义”
- github - Github Actions/workflow_run/outputs
- javascript - 如果它是空的,我该如何隐藏
- python - flask db migrate 不更改列设置
- java - 是否有可能在运行时添加自定义 Spring Boot 指标标签?
- javascript - 使用@xstate/test “缺少事件配置”
- javascript - 将从 javascript 提示收集的数据写入引导卡
- excel - 从 1 个工作表复制到另一个工作表,再复制到另一个工作表!VBA