Home >Web Front-end >CSS Tutorial >How to Prevent Image Overlap on Hover Using CSS and HTML?

How to Prevent Image Overlap on Hover Using CSS and HTML?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-23 16:32:14356browse

How to Prevent Image Overlap on Hover Using CSS and HTML?

Fixing Image Overlap on Hover with CSS/HTML

When attempting to change an image on hover using CSS and HTML, it's not uncommon to encounter issues where the original image remains visible or the new image appears improperly scaled. Here's how to resolve this problem:

In your HTML, you have an element with the ID "Library":

<img src="LibraryTransparent.png">

And in your CSS, you have the following style rules:

#Library {
    height: 70px;
    width: 120px;
}

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

The issue here is that while you're changing the background image for the hover state, you're not hiding the original image. To fix this, you can use the display property to make the original image invisible on hover:

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

Alternatively, you can use JavaScript to change the src attribute of the element on hover:

document.getElementById("Library").onmouseover = function() {
  this.src = 'LibraryHoverTrans.png';
};

document.getElementById("Library").onmouseout = function() {
  this.src = 'LibraryTransparent.png';
};

By implementing one of these solutions, you can ensure that the original image is hidden and the new image appears correctly scaled when you hover over the image.

The above is the detailed content of How to Prevent Image Overlap on Hover Using CSS and HTML?. 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