如何用 CSS 建立影像覆蓋懸停幻燈片效果?
當頁面載入時,影像覆蓋幻燈片效果會被隱藏,當滑鼠懸停在影像上時,此效果會顯示。使用 transition 屬性設定 ease-in-outtransition 效果,以實現覆蓋幻燈片效果。讓我們來看一下如何使用 HTML 和 CSS 建立一個影像覆蓋懸停幻燈片效果。
設定卡片容器
為卡片文字、影像和標題設定一個父 div −
<div class="card-container">
<img src="https://www.gstatic.com/webp/gallery/4.sm.jpg">
<div class="overlay">
<div class="caption">Tree</div>
</div>
</div>
定位卡片容器
使用 position 屬性將卡片容器定位為相對位置 −
.card-container {
position: relative;
width: 50%;
}
懸浮效果
為覆蓋設定緩入緩出效果,使用 transition 屬性。覆蓋的位置設定為絕對位置 −
.overlay {
position: absolute;
bottom: 100%;
background-color: rgb(55, 74, 179);
overflow: hidden;
width: 100%;
height: 0;
transition: .5s ease-in-out;
}
標題
使用絕對位置放置當滑鼠懸停在容器上時顯示的標題 −
.caption {
color: white;
font-size: 30px;
position: absolute;
top: 50%;
left: 50%;
text-align: center;
}
示例
以下是使用 CSS 建立影像覆蓋懸停幻燈片效果的程式碼 −
<!DOCTYPE html>
<html>
<head>
<style>
.card-container {
position: relative;
width: 50%;
}
img {
display: block;
width: 100%;
}
.overlay {
position: absolute;
bottom: 100%;
background-color: rgb(55, 74, 179);
overflow: hidden;
width: 100%;
height: 0;
transition: .5s ease-in-out;
}
.card-container:hover .overlay {
bottom: 0;
height: 100%;
}
.caption {
color: white;
font-size: 30px;
position: absolute;
top: 50%;
left: 50%;
text-align: center;
}
</style>
</head>
<body>
<h1>Image Overlay Slide Example</h1>
<div class="card-container">
<img src="https://www.gstatic.com/webp/gallery/4.sm.jpg">
<div class="overlay">
<div class="caption">Tree</div>
</div>
</div>
</body>
</html>
廣告
資料結構
計算機網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP