首页 > 解决方案 > 仅悬停覆盖图像上的 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;
  }

链接到 CodePen

标签: htmlcssbootstrap-4

解决方案


问题是您的所有元素都在同一个容器中。“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;
  }

代码笔


推荐阅读