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

Using the opacity property

In this approach, we directly set the opacity of the image using the opacity property. When the image is hovered over, its opacity gradually changes, creating the desired effect.

Example: This example shows how to use CSS to alter an image’s opacity when it hovers over. The opacity of the image starts at 1 and smoothly increases to 0.5 when it is hovered over.

HTML
<!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 {
            opacity: 1;
            transition: opacity 0.3s ease;
        }

        .image:hover {
            opacity: 0.5;
        }
    </style>
</head>

<body>
    <img class="image" 
         src="your-image.jpg" 
         alt="Your Image">
</body>

</html>

Output:

Using the opacity property

Using the :hover Pseudo-class

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.

HTML
<!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:

Using the :hover Pseudo-class