如何使用 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">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.tw/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