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
Release: 2024-12-23 16:32:14
Original
326 people have browsed it

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">
Copy after login

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;
}
Copy after login

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;
}
Copy after login

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';
};
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template