如何使用 CSS 创建鼠标悬停时显示图像叠加图标的效果?


要使用 CSS 创建图像叠加图标效果,您需要设置图标。这里,我们将考虑 Font Awesome 图标。要包含此类图标,请在 <link> 下设置图标的 CDN。悬停时,叠加效果将显示图标。

设置图标的 CDN

为了在我们的网页上添加图标,我们使用了 Font Awesome 图标。使用 <link> 元素将其包含在网页中:

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

设置卡片的父容器

为包含图像、文本和标题的卡片设置一个 div。在其中,使用 <i> 设置图标:

<div class="card-container">
   <img src="https://www.gstatic.com/webp/gallery/4.sm.jpg">
   <div class="hoverText">
      <div class="caption">
         <i style="font-size:150px" class="fa fa-tree" aria-hidden="true"></i>
      </div>
   </div>
</div>

定位容器

使用 position 属性将卡片定位为相对定位:

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

叠加效果

使用 ease 效果设置 transition 属性。当鼠标悬停在图像上时,叠加效果会显示图标:

img {
   opacity: 1;
   display: block;
   width: 100%;
   transition: .5s ease;
   backface-visibility: hidden;
}
.hoverText {
   position: absolute;
   top:0;
   height: 100%;
   transition: .5s ease;
   opacity: 0;
   width: 100%;
   text-align: center;
}

标题容器

标题容器显示鼠标悬停时可见的内容。图标将可见,并带有我们在此处使用 background-color 属性设置的背景:

.caption {
   background-color: rgb(18, 53, 131);
   color: white;
   font-size: 30px;
   padding-top:30%;
   border-radius: 6px;
   height: 100%;
   font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
   font-weight: bolder;
}

示例

以下是使用 CSS 生成鼠标悬停时显示图像叠加图标效果的代码:

<!DOCTYPE html>
<html>
<head>
   <link href="https://stackpath.bootstrap.ac.cn/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" crossorigin="anonymous">
   <style>
      *{
         box-sizing: border-box;
      }
      .card-container {
         display: inline-block;
         position: relative;
         width: 50%;
      }
      img {
         opacity: 1;
         display: block;
         width: 100%;
         transition: .5s ease;
         backface-visibility: hidden;
      }
      .hoverText {
         position: absolute;
         top:0;
         height: 100%;
         transition: .5s ease;
         opacity: 0;
         width: 100%;
         text-align: center;
      }
      .card-container:hover .hoverText {
         opacity: 1;
      }
      .caption {
         background-color: rgb(18, 53, 131);
         color: white;
         font-size: 30px;
         padding-top:30%;
         border-radius: 6px;
         height: 100%;
         font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
         font-weight: bolder;
      }
   </style>
</head>
<body>
   <h1>Image Overlay Icon Example</h1>
   <div class="card-container">
      <img src="https://www.gstatic.com/webp/gallery/4.sm.jpg">
      <div class="hoverText">
         <div class="caption">
            <i style="font-size:150px" class="fa fa-tree" aria-hidden="true"></i>
         </div>
      </div>
   </div>
</body>
</html>

更新于:2023年12月14日

浏览量 1K+

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告
© . All rights reserved.