Home > Web Front-end > CSS Tutorial > How Can I Hide or Replace Broken Images Using CSS and HTML?

How Can I Hide or Replace Broken Images Using CSS and HTML?

DDD
Release: 2024-12-05 21:05:15
Original
718 people have browsed it

How Can I Hide or Replace Broken Images Using CSS and HTML?

Hiding Broken Image Placeholders with CSS/HTML

Despite the limitations of CSS and HTML in detecting broken image links, there are minimal workarounds to conceal or manage such instances.

Hiding Broken Images

To obscure broken image placeholders, you can utilize the onerror attribute within the tag:

<img src="Error.src" onerror="this.style.display='none'" />
Copy after login

With this attribute, when an image fails to load, its display will be hidden.

Replacing with a Backup Image

Alternatively, you can specify a fallback image in case of broken links:

<img src="Error.src" onerror="this.src='fallback-img.jpg'" />
Copy after login

When an image fails to load, the source will be switched to the specified fallback image.

Note: While CSS and HTML alone cannot distinguish between broken and valid images, the onerror attribute can be useful for handling broken image placeholders in both cases.

Additional Options

For managing multiple broken images across your site, JavaScript provides a more robust solution. You can attach an event listener to the DOM and apply the same logic to all images on the page:

document.addEventListener("DOMContentLoaded", function(event) {
   document.querySelectorAll('img').forEach(function(img){
      img.onerror = function(){this.style.display='none';};
   })
});
Copy after login

This script will apply the display: none style to all broken images after the DOM has fully loaded.

The above is the detailed content of How Can I Hide or Replace Broken Images 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template