如何使用 CSS 建立滑鼠懸停時的影像疊加縮放效果?


當滑鼠游標懸停在影像上時,滑鼠懸停時的影像疊加縮放效果會在影像上顯示。為此,使用 :hover 選擇器。需要使用 transition 屬性為疊加縮放設定過渡效果。讓我們看看如何使用 HTML 和 CSS 建立滑鼠懸停時的影像疊加標題。

設定容器

設定一個容器 div。在其中,為疊加層的子 div 設定一個影像 -

<div class="card-container">
   <img src="https://tutorialspoint.tw/assets/profiles/123055/profile/200_187394-1565938756.jpg">
   <div class="overlay">
      <div class="caption">Amit</div>
   </div>
</div>

設定疊加層和標題的 div

如上所示,為疊加層設定了一個子 div。在其中,還設定了標題的容器 -

<div class="overlay">
   <div class="caption">Amit</div>
</div>

定位容器 div

將容器 div 的位置設定為相對 -

The position of the container div is set to relative:
.card-container {
   position: relative;
   width: 50%;
}

設定影像樣式

將影像設定為 100% 寬度 -

img {
   display: block;
   width: 100%;
}

定位疊加層

使用 position 屬性和絕對值來定位疊加層。使用 transition 屬性和 ease-in-out 效果設定過渡效果。scale() 設定為 0 -

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

懸停時縮放

使用 :hover 選擇器來設定懸停屬性。使用 transform 屬性將 scale() 設定為 1,以便在放置滑鼠游標時允許縮放 -

.card-container:hover .overlay {
   height: 100%;
   transform: scale(1);
}

定位標題

懸停時,標題也可見。使用 position 屬性和絕對值將其定位為絕對 -

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

示例

以下是建立滑鼠懸停時的影像疊加縮放效果的程式碼 -

<!DOCTYPE html>
<html>
<head>
   <style>
      .card-container {
         position: relative;
         width: 50%;
      }
      img {
         display: block;
         width: 100%;
      }
      .overlay {
         position: absolute;
         top:0;
         bottom: 0;
         left: 0;
         right: 0;
         background-color: rgb(55, 74, 179);
         overflow: hidden;
         width: 100%;
         height: 0;
         transform:scale(0);
         transition: .5s ease-in-out;
      }
      .card-container:hover .overlay {
         height: 100%;
         transform: scale(1);
      }
      .caption {
         color: white;
         font-size: 30px;
         position: absolute;
         top: 40%;
         left: 40%;
         text-align: center;
      }
   </style>
</head>
<body>
   <h1>Image Overlay Zoom Example</h1>
   <div class="card-container">
      <img src="https://tutorialspoint.tw/assets/profiles/123055/profile/200_187394-1565938756.jpg">
      <div class="overlay">
         <div class="caption">Amit</div>
      </div>
   </div>
</body>
</html>

更新於: 2023-12-14

682 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告