如何用 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>
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP