Front-End Development Building an Image Upload Feature with JavaScript Mastering Image Alignment: Centering Images with HTML & CSS Adding Video to Your React Native App with react-native-video HTML Image Slider: Do It Yourself and 1-Step Image Gallery Widget How to Effectively Manage Digital Assets in a PHP Image Gallery Introducing Angular Image Editor: Your New Editing Too Mastering Javascript Image Annotation Mastering JavaScript Image Popup Python Video Player: 3 Free Options and a Quick Tutorial Image Recognition Machine Learning: Use Cases and Common Algorithms HTML/CSS: How to Center Images Vertically and Horizontally How to Create an Image Map Understand CSS Background Position with 4 Simple Examples Java for Image Processing: 4 Libraries You Should Know Python Video Processing: 6 Useful Libraries and a Quick Tutorial Blur Image CSS: Two Ways to Blur Images for Gorgeous Effects Designing a Video Flipping App for Android Build an App for Embedding Video Watermarks on Android Devices Change Image on Hover with HTML and CSS How to Align Images with CSS Full Page Background Image with CSS: Tutorial and 5 Automation Tips Using CSS to Scale Page Elements and a Better Way to Scale Your Images CSS Background Image: Quick Tutorial and 3 Automation Tips Featured Image: Best Practices to Feature Images on Your Website Image Gallery Websites: Tips and Tricks for a Stunning Image Gallery 6 Ways to Stretch a Background Image with CSS Auto Cropping for Images and Video: Features & Best Practices FLAC vs. WAV: 4 Key Differences and How to Choose Converting Audio to Video: A Practical Guide FLAC vs. AIFF: 5 Key Differences and How to Choose FLAC vs. MQA: 5 Key Differences and How to Choose Converting WAV Files To OGG The Ultimate Guide On Converting OGG Files To WAV Sound Choices: FLAC vs. MP3 AAC vs MP3 – The Future of Audio Files All about AIFF and how it compares to WAV and MP3 Integrating Cloudinary with Netlify Integrating Cloudinary with Svelte and SvelteKit Integrating Cloudinary with Nuxt Integrating Cloudinary with Gatsby File Upload as a Service: How It Works and 5 Leading Solutions Native Mobile App Development Creative Uses for CSS Inner Border and 3 Ways to Set a Border Integrating Cloudinary with Next.js Front-End Development: The Complete Guide

Change Image on Hover with HTML and CSS

change image on hover html

What Is :hover in HTML and CSS?

In HTML-based web development, you may often use the :hover pseudo-class to create interactive elements on web pages. The :hover selector in CSS selects elements when you mouse over them. These elements can be anything from links and images to paragraphs and divs. When you apply the :hover pseudo-class to an element, you can change its properties, such as color, size, position, or the entire image.

An interesting way to use the :hover pseudo-class is to change an element’s image when the user hovers over it. This feature often creates engaging and interactive visuals on a webpage. It adds a touch of dynamism and interactivity to otherwise static web pages.

This is part of a series of articles about CSS Image.

In this article:

Benefits of Adding Image Hover Effects in HTML

There are numerous benefits to adding hovering effects in HTML, including the ability to change images.

Enhanced Visual Appeal

Adding hovering effects, especially the ability to change images on hover, significantly enhances a website’s visual appeal. It allows for a more dynamic interaction with the site, where images can transform to highlight information, showcase alternative views, or simply serve as a visual treat.

Improved User Interaction

Using hover effects improves user interaction by providing immediate feedback to users about their actions or choices. When an image changes upon hovering, it shows users they can interact with that element. This visual cue can be instrumental in guiding users toward making certain decisions, like clicking on a link or button. It also adds a layer of interactivity that can make navigation more interesting and engaging.

Improved Usability

These hover effects can also improve a website’s usability. By changing images on hover, web designers can use visual cues to indicate actionable items or provide additional information without cluttering the page. For example, a product image that changes to show a different angle or color option on hover can help users make informed decisions without needing to navigate away from the current page.

Related content: Read our guide to HTML image slider

change image on hover html

How to Change Image on Hover with HTML and CSS

Let’s look at how to implement the :hover feature in CSS to change images.

Method 1: Change Image on Hover Using the background-image Property

You can use the background-image property in CSS to change an image when hovering over it. This approach involves setting a background image for a block-level element (like a div or button) and changing it when the user hovers over that element.

Our HTML is simple and looks like this:

<div class="image-hover"></div>

Then, in our CSS file, we should have something like this:

.image-hover {
    width: 300px; /* Specify the width */
    height: 200px; /* Specify the height */
    background-image: url('default-image.jpg'); /* Initial background image */
    background-size: cover; /* Cover the entire area of the element */
    transition: background-image 0.5s ease-in-out; /* Smooth transition */
}

.image-hover:hover {
    background-image: url('hover-image.jpg'); /* Change on hover */
]

change image on hover html

change image on hover html

In this method, the .image-hover class is assigned to a div that initially displays default-image.jpg as its background. Upon hovering, the background image changes to hover-image.jpg. The transition property is used to ensure that the image change occurs smoothly, enhancing the user experience.

Method 2: Change Image on Hover Using the Display Property

Another approach is to use two separate image elements and control their visibility with the display property in CSS.

This method provides more flexibility regarding the content structure and can be useful when the images contain links or additional interactive elements.

Our HTML should look a little like this, including both of our images in <div> elements:

    <div class="imageBox">
      <div class="imageInn">
        <img src="cat_img.jpg"  alt="Default Image">
      </div>
      <div class="hoverImg">
        <img src="loading.png" alt="Profile Image">
      </div>
    </div>

Then, using some in-line styling, we can add this to our HTML:

      <style>

    .imageBox {
      position: relative;
      float: left;
    }

    .imageBox .hoverImg {
      position: absolute;
      left: 0;
      top: 0;
      display: none;
    }

    .imageBox:hover .hoverImg {
      display: block;
    }

    .imageBox:hover .hoverImg {
        display: block;
    }

      </style>

In this setup, both the default and hover images are placed within a .image-wrapper container. The .hover-image is initially hidden using display: none;. When the user hovers over the .image-wrapper, CSS rules hide the .default-image and display the .hover-image instead.

This method allows for more complex interactions, such as independently adding animations or hover effects to each image.

Automatically Rescaling Images for Interactive Elements with Cloudinary

When creating interactive elements with images on your web pages, you will need to deliver images that are precisely resized and cropped to the required size. This gets more complex in a responsive website because you need to provide different images for different screen sizes and layouts.

Cloudinary is a cloud-based media management service with a generous free plan that simplifies working with images and videos. It allows users to perform various operations on their media files, including resizing, cropping, and optimization, through a simple URL-based interface or via SDKs for all popular programming languages. 

URL parameters are the key-value pairs included in the URL that instruct Cloudinary on how to manipulate and deliver the requested image or video. Using these parameters, you can easily apply a wide range of transformations to your media files without needing manual intervention or additional server-side processing.

Let’s see how to effortlessly resize and rescale background images with Cloudinary. To try out the instructions below with your own images, sign up for a free Cloudinary account and upload the image to Cloudinary.

Limit Images to Specific Dimensions

To limit the size of an image to certain dimensions, change the crop value (c in URLs) to limit (c_limit).

Below is an image resized from 850 x 565 px. to 70 x 70 px, with the limit option. Due to the preserved aspect ratio, this display is 70 x 47 px.

While this might sound similar to rescaling images with CSS, there is a crucial difference. Cloudinary resizes the image on the server side and delivers it to the client in its smaller size. You can’t do that with CSS, which makes a huge difference in page load time.

https://res.cloudinary.com/demo/image/upload/w_70,h_70,c_limit/cashew_chicken.jpg

change image on hover html

Learn more in the Cloudinary Cookbook

Crop Images With Auto Gravity

While resizing images, crop the images with Cloudinary’s intelligent auto-gravity features to focus on certain details—faces, objects, color contrasts, and more. The parameter to set is gravity (g in URLs), which offers an auto value (g_auto) that intelligently crops according to your image’s content.

Cloudinary automatically crops images with content-aware, AI-based features by selecting faces, individual features, or areas of interest. This example with the g_auto setting crops the most interesting area, as determined by AI:

change image on hover html

https://res.cloudinary.com/demo/image/upload/c_crop,g_auto,h_250,w_200/docs/hot-air-balloons.jpg

Learn more about gravity-based cropping in our tutorial

Automatically Optimize Image Quality

Cloudinary’s quality parameter (q in URLs) has an auto option (q_auto) that automatically compresses and tunes images to the smallest-possible image size without sacrificing image quality.

Here’s how it works. You add the q_auto parameter to the image URL. Cloudinary’s intelligent quality and encoding algorithm assesses the image content, format, and viewing browser. The algorithm identifies the optimal quality-compression level and encoding settings, compressing and encoding the image in the best way possible for each individual user.

This process ensures that websites, browsers, viewers, and devices are served with a compressed version of a superior-quality visual. Below is an example. If you view this example on a modern browser instead of the JPG image, you will see the image loads as a modern WebP image with a much smaller size.

https://res.cloudinary.com/demo/image/upload/q_auto_woman.jpg

change image on hover html

See more examples of quality optimization on our demo page.

Sign up for a free Cloudinary account to get these features and much more.

QUICK TIPS
Colby Fayock
Cloudinary Logo Colby Fayock

In my experience, here are tips that can help you better implement image hover effects using HTML and CSS:

  1. Use opacity for smoother transitions
    Instead of completely swapping images on hover, fade between the default and hover images using opacity. This creates a more seamless and visually appealing effect, enhancing the user experience without abrupt changes.
  2. Preload hover-state images
    Preloading hover images prevents any delay when users hover over an element. This ensures that the image transition is smooth and immediate, rather than waiting for the image to load, which can disrupt the interaction.
  3. Experiment with subtle transformations
    Combine hover effects with slight image transformations such as zooming, rotating, or shifting the position. Small changes in scale or rotation on hover can make interactions more engaging without overwhelming the user.
  4. Optimize for mobile interactions
    On mobile devices, hover effects can be tricky since there’s no “hover” interaction. Ensure that the experience gracefully degrades, meaning that mobile users can still interact with the images in a meaningful way, perhaps with tap-based changes.
  5. Limit hover effects to critical elements
    Not all images should have hover effects. Use hover interactions strategically on elements that benefit from it, such as product images, CTAs, or links, to avoid cluttering the interface with too much animation.
  6. Ensure performance with lightweight assets
    Hover effects should be fast and responsive. Using optimized images (small in size but high in quality) ensures that the image swaps happen without slowing down the page, particularly important for users with slower internet connections.
  7. Maintain visual hierarchy
    When applying hover effects, ensure the rest of the page’s visual hierarchy remains intact. Hover images should not disrupt the overall layout or distract users from the main content or calls to action.
  8. Apply CSS transitions for a polished feel
    Adding smooth transitions when switching images helps create a professional, polished look. Gradual changes improve the aesthetic and make the interaction feel more natural, enhancing the overall user experience.
  9. Test across different browsers
    Ensure that your hover effects are consistent across major browsers, including older versions. Some CSS properties may behave differently or have limited support, so cross-browser testing is critical for a uniform experience.
  10. Consider accessibility
    Hover effects should not be the only means of delivering critical information. Ensure that all users, including those using screen readers or those with limited mobility, can still access the content through other mechanisms, such as click or focus events.
Last updated: Aug 24, 2024