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


当鼠标光标悬停在图像上时,鼠标悬停时的图像叠加缩放效果会在图像上显示。为此,使用 :hover 选择器。需要使用 transition 属性为叠加缩放设置过渡效果。让我们看看如何使用 HTML 和 CSS 创建鼠标悬停时的图像叠加标题。

设置容器

设置一个容器 div。在其中,为叠加层的子 div 设置一个图像 -

<div class="card-container"> <img src="https://tutorialspoint.com/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>

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

定位容器 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; }

示例

以下是创建鼠标悬停时的图像叠加缩放效果的代码 -

Open Compiler
<!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.com/assets/profiles/123055/profile/200_187394-1565938756.jpg"> <div class="overlay"> <div class="caption">Amit</div> </div> </div> </body> </html>

更新于: 2023-12-14

682 次查看

开启你的 职业生涯

通过完成课程获得认证

立即开始
广告