Hiệu ứng box-shadow trên hover ảnh
Thuộc tính box-shadow tạo bóng đổ cho box model. Kết hợp với `:hover` và `transition` tạo hiệu ứng nâng lên (elevation) khi di chuột qua.
Ví dụ cơ bản
<!DOCTYPE html>
<html>
<head>
<style>
img {
border: 2px solid orange;
border-radius: 3px;
padding: 7px;
background: white;
transition: box-shadow 0.3s ease, transform 0.3s ease;
}
img:hover {
box-shadow: 0 0 2px 2px blue; /* Bóng xanh: x y blur spread color */
transform: translateY(-2px); /* Nâng nhẹ lên */
}
</style>
</head>
<body>
<img src="coding_ground_home.jpg" alt="Online Compiler" width="300" height="300">
</body>
</html>
Phân tích box-shadow
box-shadow:
<offset-x> <offset-y> <blur-radius> <spread-radius>? <color> <inset>?;
/* Ví dụ: */
box-shadow: 0 0 2px 2px blue;
/* offset-x: 0, offset-y: 0 (giữa)
blur: 2px, spread: 2px (mở rộng bóng 2px mọi hướng)
color: blue */
Các loại bóng phổ biến
| Hiệu ứng | CSS |
|---|---|
| Bóng mờ đều (Glow) | box-shadow: 0 0 10px 5px rgba(0, 100, 255, 0.5); |
| Bóng đổ tự nhiên (Elevation) | box-shadow: 0 4px 12px rgba(0,0,0,0.15); |
| Bóng sâu (Material Design) | box-shadow: 0 8px 24px rgba(0,0,0,0.12), 0 4px 8px rgba(0,0,0,0.08); |
| Bóng inset (Nhấn chìm) | box-shadow: inset 0 2px 4px rgba(0,0,0,0.1); |
| Multiple shadows | box-shadow: 0 1px 2px rgba(0,0,0,0.1), 0 4px 8px rgba(0,0,0,0.1); |
| Border glow (không blur) | box-shadow: 0 0 0 3px blue; (spread only) |
Hover Effect Nâng Cao
.image-card {
border-radius: 8px;
overflow: hidden;
transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1),
box-shadow 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}
.image-card:hover {
transform: translateY(-4px) scale(1.02);
box-shadow:
0 12px 24px rgba(0,0,0,0.12),
0 4px 8px rgba(0,0,0,0.08);
}
.image-card img {
display: block;
width: 100%;
height: auto;
transition: transform 0.5s ease;
}
.image-card:hover img {
transform: scale(1.05); /* Zoom nhẹ ảnh bên trong */
}
Lưu ý hiệu suất
- Chỉ animate `transform` và `opacity` (GPU). `box-shadow` animate trên CPU - có thể gây lag nếu quá nhiều element.
- Dùng `will-change: transform, box-shadow` cho animation phức tạp.
- `filter: drop-shadow()` tuân theo hình dạng ảnh (transparent areas) - tốt cho PNG transparent.