如何使用 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">Amit</div> </div>
定位容器 div
将容器 div 的位置设置为 relative -
.card-container {
position: relative;
width: 50%;
}
设置图像样式
将图像高度设置为 auto,宽度设置为 100% -
.image {
display: block;
width: 100%;
height: auto;
}
定位叠加
使用 position 属性和值 absolute 定位叠加。过渡效果也设置为 ease,即以缓慢的开始,然后加速,最后缓慢结束 -
.overlay {
position: absolute;
bottom: 0;
background: rgba(48, 9, 155, 0.5);
width: 70%;
transition: .5s ease;
opacity:0;
color: rgb(251, 255, 0);
font-size: 25px;
font-weight: bolder;
padding: 20px;
text-align: center;
}
鼠标悬停时显示叠加标题
使用 :hover 选择器设置 hover 属性。悬停时,使用 opacity 属性将不透明度设置为 1 -
.card-container:hover .overlay {
opacity: 1;
}
示例
以下是使用 CSS 创建鼠标悬停时显示图像叠加标题的代码 -
<!DOCTYPE html>
<html>
<head>
<style>
* {box-sizing: border-box;}
.card-container {
position: relative;
width: 50%;
}
.image {
display: block;
width: 100%;
height: auto;
}
.overlay {
position: absolute;
bottom: 0;
background: rgba(48, 9, 155, 0.5);
width: 70%;
transition: .5s ease;
opacity:0;
color: rgb(251, 255, 0);
font-size: 25px;
font-weight: bolder;
padding: 20px;
text-align: center;
}
.card-container:hover .overlay {
opacity: 1;
}
</style>
</head>
<body>
<h2>Image Overlay Title Example</h2>
<div class="card-container">
<img src="https://tutorialspoint.com/assets/profiles/123055/profile/200_187394-1565938756.jpg" >
<div class="overlay">Amit</div>
</div>
</body>
</html>
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP