How to use the :hover Pseudo-class In CSS
This approach utilizes the :hover pseudo-class to target the image when it is being hovered over. By changing the opacity within the :hover state, we achieve the desired effect.
Example: This example showcases an alternative approach by adding an overlay over the image using absolute positioning. Initially, the overlay is transparent (opacity: 0). When the image container is hovered over, the overlay gradually becomes opaque (opacity: 1), creating a hover effect.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Image Opacity on Hover</title>
<style>
.image-container {
position: relative;
display: inline-block;
}
.overlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.5);
opacity: 0;
transition: opacity 0.3s ease;
}
.image-container:hover .overlay {
opacity: 1;
}
</style>
</head>
<body>
<div class="image-container">
<img src="./image.png"
alt="Your Image">
<div class="overlay"></div>
</div>
</body>
</html>
Output:
How to Change Image Opacity on Hover using CSS ?
Changing the opacity of an image on hover can add a more elegant and interactive effect to your website. This simple yet effective technique can be implemented using CSS. When a user hovers over an image, it gradually becomes more transparent, pointing out the interaction and creating an attractive look.
These are the following approaches:
Table of Content
- Using the opacity property
- Using the :hover Pseudo-class