Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> CSS

วิธีสร้าง Image Overlay Hover Effect (เอฟเฟกต์ทับรูปภาพเมื่อ Hover) ด้วย CSS

สร้างเอฟเฟกต์ Overlay บนรูปภาพเมื่อ Hover: รูปจางลง (Opacity) และแสดงข้อความ/ไอคอนตรงกลาง ใช้ Transition ทำให้สลม

ตัวอย่างโค้ด

<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <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://i.picsum.photos/id/237/536/354.jpg"> <div class="hoverText"> <div class="caption">Dog</div> </div> </div> </body> </html>

หลักการทำงาน

  1. .card-container { position: relative; } - จุดอ้างอิงสำหรับ Absolute positioning
  2. img { transition: .5s ease; } - ทรานซิชัน Opacity
  3. .hoverText { position: absolute; top: 50%; left: 40%; opacity: 0; transition: .5s; } - ซ่อนไว้ ตรวจกลาง (ประมาณ)
  4. .card-container:hover img { opacity: 0.4; } - Hover Container -> รูปจาง
  5. .card-container:hover .hoverText { opacity: 1; } - Hover Container -> โชว์ข้อความ

ปรับปรุงการจัดกึ่งกลางแท้

.hoverText {
  top: 50%; left: 50%;
  transform: translate(-50%, -50%);
}

ผลลัพธ์

รูปสุนัข ปกติชัดเจน Hover -> รูปจาง 40% แสดงกล่องสีน้ำเงินเขียน "Dog" ตรงกลาง