Change the image URL on hover using CSS only
I want to change the image src when hovering over the image without using JavaScript. Is it possible to achieve this using CSS only?
✅ Yes, you can change the image src using css only.
You can use the CSS :hover pseudo-class to apply styles when an element is being hovered over. However, changing the src attribute directly is not possible with CSS alone. Instead, you can use the CSS content property
.sad-emoji:hover { content: url('happy-emoji.png'); }
Demo:
Hover the image.
In CSS (Cascading Style Sheets), the content property is used to insert content generated by the CSS before or after an element's actual content. The url() function is commonly used within the content property to specify the location of an image file. So this trick, I am not sure whether all browsers support it or not.
The content property in this context is being used to dynamically change the content of the selected element when it is being hovered over. In this case, it is setting the content to an image specified by the URL 'happy-emoji.png'. So, when you hover over an element with the class sad-emoji, it will change its content to the image of a happy emoji.