如何用 CSS 製作影像疊加懸停效果?


影像懸停時的疊加效果在頁面載入時隱藏,當滑鼠游標懸停在影像上時可見。易於過渡效果的設定透過使用過渡屬性來實現疊加效果。讓我們來看看如何使用 HTML 和 CSS 建立影像疊加懸停效果。

設定卡片容器

為卡片文字、影像和標題設定一個父級 div −

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

定位卡片容器

卡片容器使用 position 屬性以相對方式定位 −

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

疊加效果

過渡設定為易於生效,使用疊加的過渡屬性。疊加的位置設定為絕對 −

.hoverText {
   transition: .5s ease;
   opacity: 0;
   position: absolute;
   top: 50%;
   left: 40%;
   text-align: center;
}

在卡片容器上懸停時,使用 opacity 屬性更改不透明度 −

.card-container:hover img {
   opacity: 0.4;
}
.card-container:hover .hoverText {
   opacity: 1;
}

疊加標題

使用 border-radius 屬性設定影像上的標題 −

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

示例

以下是使用 CSS 建立影像疊加懸停效果的程式碼 −

<!DOCTYPE html>
<html>
<head>
   <style>
      .card-container {
         display: inline-block;
         position: relative;
         width: 50%;
      }
      img {
         opacity: 1;
         display: block;
         width: 100%;
         transition: .5s ease;
         backface-visibility: hidden;
      }
      .hoverText {
         transition: .5s ease;
         opacity: 0;
         position: absolute;
         top: 50%;
         left: 40%;
         text-align: center;
      }
      .card-container:hover img {
         opacity: 0.4;
      }
      .card-container:hover .hoverText {
         opacity: 1;
      }
      .caption {
         background-color: rgb(18, 53, 131);
         color: white;
         font-size: 30px;
         padding: 20px;
         border-radius: 6px;
         font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
         font-weight: bolder;
      }
   </style>
</head>
<body>
   <h1>Image Overlay effect Example</h1>
   <div class="card-container">
      <img src="https://www.gstatic.com/webp/gallery/4.sm.jpg">
      <div class="hoverText">
         <div class="caption">Tree</div>
      </div>
   </div>
</body>
</html>

更新於: 2023-12-14

1K+ 瀏覽量

開啟您的 職業生涯

透過完成課程獲得認證

開始
廣告