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

วิธีสร้าง Image Overlay Zoom Effect (ซูมทับรูป) เมื่อ Hover ด้วย CSS

สร้างเอฟเฟกต์ Overlay ที่ Zoom ขยายจากศูนย์ (Scale 0 -> 1) ครอบคลุมรูปภาพทั้งหมดเมื่อ Hover ใช้ Transform Scale

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

<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> .card-container {    position: relative;    width: 50%; } img {    display: block;    width: 100%; } .overlay {    position: absolute;    top:0;    bottom: 0;    left: 0;    right: 0;    background-color: rgb(55, 74, 179);    overflow: hidden;    width: 100%;    height: 0;    transform:scale(0);    transition: .5s ease-in-out; } .card-container:hover .overlay {    height: 100%;    transform: scale(1); } .caption {    color: white;    font-size: 30px;    position: absolute;    top: 50%;    left: 50%;    text-align: center; } </style> </head> <body> <h1>Image Overlay Zoom Example</h1> <div class="card-container"> <img src="https://i.picsum.photos/id/237/536/354.jpg"> <div class="overlay"> <div class="caption">Dog</div> </div> </div> </body> </html>

หลักการ Zoom Effect

  1. Initial: height: 0; transform: scale(0); - Overlay หดเหลี่ยมจุด
  2. Hover: height: 100%; transform: scale(1); - ขยายครอบเต็มรูป
  3. top:0; bottom:0; left:0; right:0; - ครอบทั้ง 4 ขอบ
  4. transition: .5s ease-in-out - Animation ขยาย/หด สลม

จัดกึ่งกลาง Caption

.caption {
  position: absolute;
  top: 50%; left: 50%;
  transform: translate(-50%, -50%);
}

ผลลัพธ์

รูปสุนัข ปกติปกติ Hover -> Overlay สีน้ำเงิน Zoom ขยายจากศูนย์กลางครอบทั้งรูป แสดง "Dog" ตรงกลาง