如何使用 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.bootstrapcdn.com/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+

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告