Home >Web Front-end >CSS Tutorial >Why Does My Hover Image Overlap Instead of Replacing the Original?

Why Does My Hover Image Overlap Instead of Replacing the Original?

Susan Sarandon
Susan SarandonOriginal
2024-12-21 07:24:09333browse

Why Does My Hover Image Overlap Instead of Replacing the Original?

Modifying Image Display with CSS/HTML Hover

When attempting to replace an image with another upon mouse hover, there may be instances where the original image remains visible or the new image fails to adjust its dimensions, causing them to overlap. Here's a look at the issue and a possible solution.

The code provided exhibits the problem:

<img src="LibraryTransparent.png">
#Library {
    height: 70px;
    width: 120px;
}

#Library:hover {
    background-image: url('LibraryHoverTrans.png');
    height: 70px;
    width: 120px;
}

In this code, setting the background image on hover ensures that the second image appears over the first but may not properly resize or position itself.

Alternative Solution: Using JavaScript

Another option is to utilize JavaScript to handle the image change:

<img src='LibraryTransparent.png' onmouseover="this.src='LibraryHoverTrans.png';" onmouseout="this.src='LibraryTransparent.png';" />

In this approach, an onmouseover event changes the image source to the alternative when the mouse hovers over, and an onmouseout event reverts the source to the original image when the mouse leaves. Using JS provides more direct control over the image manipulation, ensuring a seamless transition between images.

The above is the detailed content of Why Does My Hover Image Overlap Instead of Replacing the Original?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn