如何用 CSS 创建图像覆盖悬停幻灯片效果?


当页面加载时,图像覆盖幻灯片效果会被隐藏,当鼠标悬停在图像上时,此效果会显示。使用 transition 属性设置 ease-in-outtransition 效果,以实现覆盖幻灯片效果。让我们来看一下如何使用 HTML 和 CSS 创建一个图像覆盖悬停幻灯片效果。

设置卡片容器

为卡片文本、图像和标题设置一个父 div −

<div class="card-container">
   <img src="https://www.gstatic.com/webp/gallery/4.sm.jpg">
   <div class="overlay">
      <div class="caption">Tree</div>
   </div>
</div>

定位卡片容器

使用 position 属性将卡片容器定位为相对位置 −

.card-container {
   position: relative;
   width: 50%;
}

悬浮效果

为覆盖设置缓入缓出效果,使用 transition 属性。覆盖的位置设置为绝对位置 −

.overlay {
   position: absolute;
   bottom: 100%;
   background-color: rgb(55, 74, 179);
   overflow: hidden;
   width: 100%;
   height: 0;
   transition: .5s ease-in-out;
}

标题

使用绝对位置放置当鼠标悬停在容器上时显示的标题 −

.caption {
   color: white;
   font-size: 30px;
   position: absolute;
   top: 50%;
   left: 50%;
   text-align: center;
}

示例

以下是使用 CSS 创建图像覆盖悬停幻灯片效果的代码 −

<!DOCTYPE html>
<html>
<head>
   <style>
      .card-container {
         position: relative;
         width: 50%;
      }
      img {
         display: block;
         width: 100%;
      }
      .overlay {
         position: absolute;
         bottom: 100%;
         background-color: rgb(55, 74, 179);
         overflow: hidden;
         width: 100%;
         height: 0;
         transition: .5s ease-in-out;
      }
      .card-container:hover .overlay {
         bottom: 0;
         height: 100%;
      }
      .caption {
         color: white;
         font-size: 30px;
         position: absolute;
         top: 50%;
         left: 50%;
         text-align: center;
      }
   </style>
</head>
<body>
   <h1>Image Overlay Slide Example</h1>
   <div class="card-container">
      <img src="https://www.gstatic.com/webp/gallery/4.sm.jpg">
      <div class="overlay">
         <div class="caption">Tree</div>
      </div>
   </div>
</body>
</html>

更新于: 14-12-2023

890 人阅读过

开启你的 职业生涯

完成课程即可获得认证

立刻开始
广告
© . All rights reserved.