312

How can I hide the broken image icon? Example: Example

I have an image with error src:

<img src="Error.src"/>

The solution must work in all browsers.

TylerH
  • 20,799
  • 66
  • 75
  • 101
Geray Suinov
  • 3,521
  • 3
  • 16
  • 19
  • 1
    I tried to set alt= "", and set to img teg background throw CSS live: {background: url(src), width:...; height:..} but it not true. My img tag must hide then src is broken. – Geray Suinov Feb 26 '14 at 19:42
  • See a possible solution here - http://stackoverflow.com/questions/18484753/how-to-hide-image-not-found-icon-on-ie-and-chrome-using-css but needs JS though. You cannot do this with CSS alone. – JohanVdR Feb 26 '14 at 19:46
  • See http://www.w3schools.com/jsref/event_onerror.asp "onerror" attribute – Amy.js Nov 22 '16 at 16:39

24 Answers24

382

There is no way for CSS/HTML to know if the image is broken link, so you are going to have to use JavaScript no matter what

But here is a minimal method for either hiding the image, or replacing the source with a backup.

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

or

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

Update

You can apply this logic to multiple images at once by doing something like this:

document.addEventListener("DOMContentLoaded", function(event) {
   document.querySelectorAll('img').forEach(function(img){
   img.onerror = function(){this.style.display='none';};
   })
});
<img src="error.src">
<img src="error.src">
<img src="error.src">
<img src="error.src">

Update 2

For a CSS option see michalzuber's answer below. You can't hide the entire image, but you change how the broken icon looks.

Community
  • 1
  • 1
Kevin Jantzer
  • 9,215
  • 2
  • 28
  • 52
  • 3
    You can do it with HTML only using the object tag since it can be used to display images just like the img tag, and doesn't display a broken link if the image doesn't exist, it works in all browsers and as far back as IE8 all by itself, you can even use default images with this method, I posted an answer with details below. – Nick Steele Jul 03 '15 at 09:09
  • 2
    This worked for me instead of the approach because I needed the image to have a declared margin, but only if a valid image was found, otherwise I needed it to take up zero space. doesn't have the onerror event, so that wasn't an option there. A style rule to remove the margin, using an :empty pseudo class, was never triggered on object. – John Hatton Sep 28 '16 at 17:22
  • I have a question. is there a way possible to give the script common to apply for every image tag on the page instead of giving this particular line of script in every image tag. thank you @Kevin jantzer – Lemdor Nov 03 '16 at 11:01
  • 1
    @Lemdor – yes, you would need to find images on load and attach the common function to each one. You could use jQuery or vanilla JS to accomplish this (I've updated my answer with an example) – Kevin Jantzer Dec 13 '16 at 21:21
  • In reactJs it is very easy to do that, same principle applies there. Found this tutorial here - https://youtu.be/90P1_xCaim4. Also adding a preloader (https://youtu.be/GBHBjv6xfY4) for image hides the transition and helping to provide a good UX. – Prem Jan 13 '19 at 16:25
  • a little bit dangerous, if someone add this.src in onerror it will not show image – Satish Patro May 09 '19 at 07:05
  • we can do without js too. Have a look at it https://stackoverflow.com/a/56053704/8609847 – Satish Patro Oct 27 '19 at 14:31
  • onerror="this.style.display='none'" worked for me – Flemming Bonde Kentved Nov 18 '22 at 17:42
189

Despite what people are saying here, you don't need JavaScript at all, you don't even need CSS!

It's actually very doable and simple with HTML only.
You can even show a default image if an image doesn't load. Here's how...

This also works on all browsers, even as far back as IE8 (out of 250,000+ visitors to sites I hosted in September 2015, ZERO people used something worse than IE8, meaning this solution works for literally everything).

Step 1: Reference the image as an object instead of an img. When objects fail they don't show broken icons; they just do nothing. Starting with IE8, you can use object and img tags interchangeably. You can resize and do all the glorious stuff you can with regular images too. Don't be afraid of the object tag; it's just a tag, nothing big and bulky gets loaded and it doesn't slow down anything. You'll just be using the img tag by another name. A speed test shows they are used identically.

Step 2: (Optional, but awesome) Stick a default image inside that object. If the image you want actually loads in the object, the default image won't show. So for example you could show a list of user avatars, and if someone doesn't have an image on the server yet, it could show the placeholder image... no JavaScript or CSS required at all, but you get the features of what takes most people JavaScript.

Here is the code...

<object data="avatar.jpg" type="image/jpeg">
    <img src="default.jpg" />
</object>

... Yes, it's that simple.

If you want to implement default images with CSS, you can make it even simpler in your HTML like this...

<object class="avatar" data="user21.jpg" type="image/jpeg"></object>

...and just add the CSS from this answer -> https://stackoverflow.com/a/32928240/3196360

Nick Steele
  • 7,419
  • 4
  • 36
  • 33
  • 6
    Somehow I completely missed this idea, when it is so obvious in retrospect! Unfortunately, I don't think the object tag can gracefully handle responsive images like we're starting to see on the img.srcset property :( – Windgazer Jan 29 '16 at 11:45
  • 2
    Great idea, thank you for that! On a side note, the object-tag is blocking the scroll wheel (in my implementation, at least) ... if this happens to you, just use `object { pointer-events: none; }` in your CSS (Source: http://stackoverflow.com/a/16534300) – DHainzl Feb 14 '16 at 22:10
  • 6
    This does break the semantics of image tags, though. I don't know if search engines will like your using of `` tags instead of `` tags. Is this approach HTML5-compliant and rendered correctly by all major browsers? – Pieter Apr 23 '16 at 10:16
  • 9
    This is HTML4 compliant (compliant since 1997) and rendered correctly by all major browsers since IE8/2009 (other browsers did it much, much earlier). If a search engine doesn't understand an object with an image type is an image, it's had 19 years to catch up to spec so it's probably not a very good engine... Teens that are on the road driving cars now weren't even conceived when this solution met specs... How far back do you want to go? :) This is a rock-solid solution. – Nick Steele Apr 25 '16 at 19:41
  • 1
    Fun fact, chrome renders an `object`-tag without the mime-type as follows: `480 (640×480)` **``** `` – yckart May 29 '16 at 19:31
  • ...safari too... **But**, it shows nothing **with** mime-type! – yckart May 29 '16 at 19:51
  • why is this is better than the above answer? – Furkan Gözükara Jun 29 '16 at 13:52
  • 6
    @MonsterMMORPG because it doesn't use JavaScript, and you aren't always allowed to (in a body of an email message, for example). – ForNeVeR Aug 31 '16 at 07:06
  • 2
    Sometime between Chrome 66 and Chrome 68, this stopped working. Chrome now shows something that almost looks like an iframe containing the html of the 404 result. – Micteu Aug 01 '18 at 16:35
  • 1
    Awesome post! W3C should make this the default implementation of the tag, not an ugly broken image icon. It's a shame we need a workaround to do something that should be obvious. – John Dec 03 '19 at 18:16
  • 3
    I really hoped it would work, but gmail web and outlook web removed object tag from html email. – elfan Sep 09 '20 at 09:33
  • @elfan, gmail and outlook now support AMP for email, which includes not only broken image support but nearly full-blown applications. AMP for email supports downgrades if the email client doesn't support it as well. There is no reason I can think of to try to use any solution on this answer page any longer. Check out the AMP playground to get started: https://playground.amp.dev/ – Nick Steele Sep 10 '20 at 17:35
  • 1
    Nice one man. Thanks for sharing. @NickSteele are there any accessibility issues I need to worry about while using this ? – Chidiebere Oct 04 '20 at 14:24
  • Sorry for the late reply Chidiebere. JAWS is the most popular screen reader, it supports the object tag or any other tag for images as long as you have an alt tag. However, this answer is now outdated if you're looking to build anything app-level for non-js implementations like HTML since AMP supports so much more. This solution is only still valid for legacy systems. – Nick Steele Feb 15 '22 at 22:38
  • 1
    @NickSteele This worked perfect for me except the image failed to load on iOS. But after changing the type from `type="image/jpg"` to `type="image/jpeg"` then it loaded in iOS perfectly. Can you update the `type` attribute in your code to `image/jpeg` instead? – Eric May 18 '22 at 14:11
  • Just a warning: From my usage, if the image URL returns an HTML page when the image is not found (eg. a single-page-app 404 page), the browser will load the HTML document as an embed (similar to an iframe) within the rather than showing nothing. – Ethan Sep 15 '22 at 01:48
  • @NickSteele the question is about html5, not the deprecated html4. – Alex78191 Sep 20 '22 at 08:27
  • @Alex78191 Can you explain a bit more? The question does not specify HTML5 anywhere, so I'm not sure what you're saying. Since HTML5 was recommended as standard in Oct 2014 and this question was asked 8 months before that, in Feb 2014, I doubt the asker wanted strictly HTML5. What is more... the solution I propose is HTML5 compliant as of 2 weeks ago, so I'm not sure what you mean? see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/object – Nick Steele Sep 30 '22 at 15:49
  • I generally love the simplicity of this approach. Only problem for me: `` seems to have very limited CSS-styling capabilities (only inline-css, `aspect-ratio` doesn't work, ...). So you can place an image with basic styles. But you can't really style it conditionally. – Sammeeey Jun 25 '23 at 07:31
  • EDIT: `aspect-ratio` is meant for use with containers, not images. Therefore it doesn't work anyway. – Sammeeey Jun 25 '23 at 08:00
102

Found a great solution at https://bitsofco.de/styling-broken-images/

img {  
  position: relative;
}

/* style this to fit your needs */
/* and remove [alt] to apply to all images*/
img[alt]:after {  
  display: block;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: #fff;
  font-family: 'Helvetica';
  font-weight: 300;
  line-height: 2;  
  text-align: center;
  content: attr(alt);
}
<img src="error">
<br>
<img src="broken" alt="A broken image">
<br>
<img src="https://images-na.ssl-images-amazon.com/images/I/218eLEn0fuL.png" alt="A bird" style="width: 120px">
Kevin Jantzer
  • 9,215
  • 2
  • 28
  • 52
michalzuber
  • 5,079
  • 2
  • 28
  • 29
  • 3
    Awesome solution purely using CSS which should be the accepted answer. The article linked to is outdated, as browser support is now 97,87%: http://caniuse.com/#feat=css-gencontent. – holm50 Nov 29 '16 at 09:02
  • 3
    The [linked article](https://bitsofco.de/styling-broken-images) has an excellent explanation on how the browsers handle images, but keep in mind that this solution works only if you have a solid background and you want to **cover everything with another box** of the same solid color, or with another image. This solution is not really removing or hiding the broken image icon, it's just covering it. – Claudio Floreani Jul 12 '17 at 14:44
  • What if we have an element and added an image using background-image? Do you know any solution for it? – Mohammad Kermani Jul 22 '17 at 12:36
  • The problem with this solution is that the alt content will shine through if the image contains transparent areas – ThomasR Nov 22 '17 at 13:04
  • 9
    On Chrome 70, it shows the bird + a broken image icon :( – Simon Arnold Nov 28 '18 at 22:11
  • 3
    ^ Same on Firefox 63 – dsturbid Nov 29 '18 at 10:17
  • 1
    @dailysleaze – On Firefox 64+, this moved to `img[alt]::before`. You can use `display:inline-block` if you like, as it's closer to the original. – Adam Katz Dec 18 '18 at 22:06
  • 1
    As mentioned above, this doesn't work anymore on major browsers, and just the fact that it can unexpectedly break if a browser ships a new version doesn't make me very confident to use this – Robin Métral May 10 '21 at 10:17
  • it just overlays the broken picture on top – Alex78191 Sep 20 '22 at 08:41
81

If you will add alt with text alt="abc" it will show the show corrupt thumbnail, and alt message abc

<img src="pic_trulli.jpg" alt="abc"/>

1st

If you will not add alt it will show the show corrupt thumbnail

<img src="pic_trulli.jpg"/>

2nd

If you want to hide the broken one just add alt="" it will not show corrupt thumbnail and any alt message(without using js)

<img src="pic_trulli.jpg" alt=""/>

If you want to hide the broken one just add alt="" & onerror="this.style.display='none'" it will not show corrupt thumbnail and any alt message(with js)

<img src="pic_trulli.jpg" alt="abc" onerror="this.style.display='none'"/>

4th one is a little dangerous(not exactly) , if you want to add any image in onerror event, it will not display even if Image exist as style.display is like adding. So, use it when you don't require any alternative image to display.

display: 'none'; // in css

If we give it in CSS, then the item will not display(like image, iframe, div like that).

If you want to display image & you want to display totally blank space if error, then you can use, but also be careful this will not take any space. So, you need to keep it in a div may be

Link https://jsfiddle.net/02d9yshw/

Satish Patro
  • 3,645
  • 2
  • 27
  • 53
  • 8
    YES! Just add `alt=""`! That is literally it! Thank you. So glad i scrolled to the bottom of the page. I'm using lazy loading, and in-frame images that haven't loaded yet (because the browser mistakenly thinks the viewport hasn't scrolled to them yet) showed as broken images. A little scroll, and they reappear. The broken images in their place were so ugly though – velkoon May 17 '20 at 10:03
  • getting rid of alt will hurt your SEO if that is important to you. img { color: transparent; } will hide the alt without alt="" so Google will still see the alt tag and you won't get dinged SEO wise – AZ Chad Jan 30 '21 at 15:38
  • 1
    This won't work if your image has set dimensions via `width` and `height`. – Robin Métral May 28 '21 at 07:44
  • 1
    @RobinMétral, in that case last approach works, css style none. . Please remove downvote if it solves your issue – Satish Patro May 28 '21 at 09:47
  • That's right, this is equivalent to [the top answer](https://stackoverflow.com/a/22051972)–it still doesn't solve my use case though, since I still need the image border to be visible, not hide it completely. Could you edit your answer to mention that the `alt=""` only works for images without set dimensions? (and obviously only for presentational images, otherwise alt is fundamental for accessibility)? – Robin Métral May 28 '21 at 12:11
  • 1
    I feel in that case you could use bootstrap class="img-thumbnail", will just let you have a border box of the desired width – Carlo May 17 '22 at 11:07
64

I think the easiest way is to hide the broken image icon by the text-indent property.

img {
    text-indent: -10000px
}

Obviously it doesn't work if you want to see the "alt" attribute.

Burnee
  • 2,453
  • 1
  • 24
  • 28
32

in case you like to keep/need the image as a placeholder, you could change the opacity to 0 with an onerror and some CSS to set the image size. This way you will not see the broken link, but the page loads as normal.

<img src="<your-image-link->" onerror="this.style.opacity='0'" />

img {
    width: 75px;
    height: 100px;
}
Ewald Bos
  • 1,560
  • 1
  • 20
  • 33
  • @adrianp can you share the link with deprecated information (list) please thanks. It still seems to work fine with style options. Btw no deprecation message on https://www.w3schools.com/jsref/event_onerror.asp Normally they update with a red message "is deprecated ...." – Ewald Bos Aug 06 '21 at 09:23
  • its been marked as deprecated on mdn, see table https://developer.mozilla.org/en-US/docs/web/html/element/img#browser_compatibility – adrianp Aug 06 '21 at 13:22
20

I liked the answer by Nick and was playing around with this solution. Found a cleaner method. Since ::before/::after pseudos don't work on replaced elements like img and object they will only work if the object data (src) is not loaded. It keeps the HTML more clean and will only add the pseudo if the object fails to load.

object {
  position: relative;
  float: left;
  display: block;
  width: 200px;
  height: 200px;
  margin-right: 20px;
  border: 1px solid black;
}
object::after {
  position: absolute;
  top: 0;
  left: 0;
  display: block;
  width: 100%;
  height: 100%;
  content: '';
  background: red url("http://placehold.it/200x200");
}
<object data="http://lorempixel.com/200/200/people/1" type="image/png"></object>

<object data="http://broken.img/url" type="image/png"></object>
Sumit
  • 2,242
  • 1
  • 24
  • 37
Bartezz
  • 474
  • 4
  • 13
  • instead of empty content, one _can_ make use of an alt-Text (just like with ``) and get to see it with`content: attr(alt);`, styling the `::after`-bracket as `display: flex; justify-content: center, …`, still has the benefit of avoiding the 'classic' broken-image-icon… or ``-tag, not sure what is considered more “barrier free”… – Frank N Oct 26 '21 at 10:49
17

If you need to still have the image container visible due to it being filled in later on and don't want to bother with showing and hiding it you can stick a 1x1 transparent image inside of the src:

<img id="active-image" src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"/>

I used this for this exact purpose. I had an image container that was going to have an image loaded into it via Ajax. Because the image was large and took a bit to load, it required setting a background-image in CSS of a Gif loading bar.

However, because the src of the was empty, the broken image icon still appeared in browsers that use it.

Setting the transparent 1x1 Gif fixes this problem simply and effectively with no code additions through CSS or JavaScript.

user2596313
  • 195
  • 1
  • 5
12

Using CSS only is tough, but you could use CSS's background-image instead of <img> tags...

Something like this:

HTML

<div id="image"></div>

CSS

#image {
    background-image: url(Error.src);
    width: //width of image;
    height: //height of image;

}

Here is a working fiddle.

Note: I added the border in the CSS on the fiddle just to demonstrate where the image would be.

MrMaavin
  • 1,611
  • 2
  • 19
  • 30
Dryden Long
  • 10,072
  • 2
  • 35
  • 47
11

The same idea as described by others works in React as follow:

<img src='YOUR-URL' onError={(e) => e.target.style.display='none' }/>
Christian Fritz
  • 20,641
  • 3
  • 42
  • 71
5

Since 2005, Mozilla browsers such as Firefox have supported the non-standard :-moz-broken CSS pseudo-class that can accomplish exactly this request:

/* for display purposes so you can see the empty cell */
td { min-width:64px; }

img:-moz-broken { display:none; }
img[src="error"]:-moz-broken { display:initial; } /* for demo purposes */
<table border="1"><tr><td>
  <img src="error">
</td><td>
  <img src="error" alt="error image">
</td><td>
  <img src="error" alt="">
</td><td>
  <img src="broken" alt="broken image">
</td><td>
  <img src="broken" alt="">
</td><td>
  <img src="https://i.stack.imgur.com/Mkdgc.png"
   alt="A bird" style="width: 120px">
</td></tr></table>

There are several cells in this example. From left to right:

  1. A broken image without alt attribute (baseline): show a broken image
  2. A broken image with alt text (baseline): show the alt text
  3. A broken image with empty alt text (baseline): show the alt text (nothing)
  4. A broken image with alt text (our CSS): hide the broken image
  5. A broken image with empty alt text (our CSS): show the alt text (nothing)
  6. A functional image with alt text (our CSS): show the image

img::before also works in Firefox 64 (though once upon a time it was img::after so this is not reliable). I can't get either of those to work in Chrome 71.

The most compatible solution would be to specify alt="" and to use the Firefox-specific CSS.

Note that a broken image with an empty alt attribute doesn't guarantee the broken image icon will be suppressed, but that does seem to be the behavior in Firefox 103 and Chromium 103. Also note that this violates accessibility guidelines since screen readers will not be able to describe items with empty alt text and that may be disruptive to blind users' experiences.

Adam Katz
  • 14,455
  • 5
  • 68
  • 83
  • 1
    Interesting ... do you know if Chrome has a similar pseudo-class? – 1000Gbps Apr 16 '20 at 15:40
  • 1
    @1000Gbps – I couldn't find one when I made that answer and can't find one now, at least with quick web queries and by looking at [mozilla bug 11011](https://bugzilla.mozilla.org/show_bug.cgi?id=11011 "Need pseudo-classes for when alt text is shown (:-moz-alt-text, :-moz-placeholder, :-moz-broken)"). You could actually [request such a thing in Chromium](https://bugs.chromium.org/p/chromium/issues/list) (the upstream for Chrome) if you want, but as it's nonstandard, there's no assurance they'll do it. – Adam Katz Apr 16 '20 at 15:46
  • I highly doubt they will do it in short time, taking into consideration that they had a hard time dealing with some nasty bugs I've reported there ... No matter the fact that built-in pseudo-classes like this one will remove from frameworks a lot of JS code written for the same reason – 1000Gbps Apr 16 '20 at 19:15
  • Tested on Firefox 104.0.2, this will work if your `` tag contain `alt=""` attribute. At least required empty `alt=""` attribute. – vee Sep 20 '22 at 06:09
  • @vee – I only made the example depend on the `alt` attribute so I could demonstrate the differences. Since that was confusing, I've reworked the example to no longer depend on attributes. – Adam Katz Sep 20 '22 at 16:44
  • @AdamKatz It's OK. I'm just add additional info in my comment to your previous code to confirm that it work but required `alt` attribute. However I'm up voted. – vee Sep 20 '22 at 17:59
4

Use the object tag. Add alternative text between the tags like this:

<object data="img/failedToLoad.png" type="image/png">Alternative Text</object>

http://www.w3schools.com/tags/tag_object.asp

ThomasAFink
  • 1,257
  • 14
  • 25
4

You can follow this path as a css solution

img {
        width:200px;
        height:200px;
        position:relative
   }
img:after {
        content: "";
        position: absolute;
        top: 0;
        left: 0;
        width: inherit;
        height: inherit;
        background: #ebebeb url('http://via.placeholder.com/300?text=PlaceHolder') no-repeat center;
        color: transparent;
    }
<img src="gdfgd.jpg">
Cenk YAGMUR
  • 3,154
  • 2
  • 26
  • 42
  • First I was thinking that this is a nice solution but this is not working on IE. Also not when adding display block in the after css – Glenn Franquet Jan 09 '19 at 16:10
1

Missing images will either just display nothing, or display a [ ? ] style box when their source cannot be found. Instead you may want to replace that with a "missing image" graphic that you are sure exists so there is better visual feedback that something is wrong. Or, you might want to hide it entirely. This is possible, because images that a browser can't find fire off an "error" JavaScript event we can watch for.

    //Replace source
    $('img').error(function(){
            $(this).attr('src', 'missing.png');
    });

   //Or, hide them
   $("img").error(function(){
           $(this).hide();
   });

Additionally, you may wish to trigger some kind of Ajax action to send an email to a site admin when this occurs.

Ali Panahian
  • 305
  • 1
  • 6
1

The trick with img::after is a good stuff, but has at least 2 downsides:

  1. not supported by all browsers (e.g. doesn't work on Edge https://codepen.io/dsheiko/pen/VgYErm)
  2. you cannot simply hide the image, you cover it - so not that helpful when you what to show a default image in the case

I do not know an universal solution without JavaScript, but for Firefox only there is a nice one:

img:-moz-broken{
  opacity: 0;
}
Dmitry Sheiko
  • 2,130
  • 1
  • 25
  • 28
1

edit: doesn't actually solve the asked issue, but might still be useful.

This is what I did with SASS/SCSS. I have utility scss file that contains this mixin:

  @mixin fallback() {
    background-image: url('/assets/imgs/fallback.png');
    background-size: cover;
    background-repeat: no-repeat;
    background-position-x: center;
    background-position-y: center;
  }

Its usage in .scss

img {
  // ...
  @include fallback();
}
O-9
  • 1,626
  • 16
  • 15
1

You can use before and after as a style to prevent the broken image.

<img src="Error.src">

img:before {
  content: url("image.jpg");
}

img:after {
  content: "(url: " attr(src) ")";
}

In this case, if the image in the src is broken, it will use the before content, and if there is no error it will use the src.

Tim S. Van Haren
  • 8,861
  • 2
  • 30
  • 34
1

I'm going to build on others' answers. Instead of hiding the tag (which may have important styling), feed it a dummy image:

<img src="nonexistent.png" onerror="this.src=`data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg'></svg>`;"/>
Nate Symer
  • 2,185
  • 1
  • 20
  • 27
0

In theory:

Strictly "css only", we have no clean options. See other answers, I have nothing to add.

In practice:

I'd say adding a class on error event is the best way to go. Here's what I mean - and there were answers almost like this, the principle is the same, it's just more elegant if you don't add the style declarations directly. Instead, add a class that can be targeted later:

   <img src="..." onerror="this.classList.add('notfound')">

And NOW you can style the hell out of it, using img.notfound as selector. You can make it a habit to add this little fragment to all your images; won't hurt anything until you style it.


Side note, before anyone comments "this is not a css-only solution": yes, thank you captain, indeed it's not. I'm trying to help with the problem itself, a problem many may have, instead of just looking at the exact wording.

dkellner
  • 8,726
  • 2
  • 49
  • 47
0

This is an old question but here is something that works, the main trick here is never set a fixed height and width on the image i only use percentage.

.example {
  background-color: #e7e7e7;
  padding: 25px;
}

.image-box {
  height: 50px;
  width: 50px;
  border-radius: 8px;
  background-color: rgb(241, 255, 255);
  color: rgb(241, 245, 249);
  overflow: hidden;
  display: block;
  position: relative;
}

.image {
  display: block;
  max-width: 100%;
  height: 100%;
  object-fit: cover;
}
<div class="example">
  <span class="image-box">
    <img class="image" src="/broken.jpeg" alt>
  </span>
</div>
Sunny
  • 103
  • 1
  • 1
  • 11
-1

Angular way of hiding the broken image.

Inside Html file

<img *ngIf="showImage" [src]="url" (error)="showImage = false">

Inside Ts file

public showImage = true;
Arun Kumar
  • 135
  • 2
  • 4
-3

Hide image alt with this

img {
   color: transparent;
}
Kamran Taghaddos
  • 452
  • 1
  • 10
  • 22
-4

A basic and very simple way of doing this without any code required would be to just provide an empty alt statement. The browser will then return the image as blank. It would look just like if the image isn't there.

Example:

<img class="img_gal" alt="" src="awesome.jpg">

Try it out to see! ;)

user45678
  • 343
  • 2
  • 6
  • 19
  • 11
    That depends on the browser. In Chrome you will still also have the image border and broken image icon in addition to the (here empty) alt text. – panzi May 06 '15 at 23:58
  • If the image is decorational and not imperative to the content an empty alt is fine. In fact it is recommended over no alt at all. Otherwise, this is highly unadvisable. A broken image is an image that cannot be seen, but if it has an alt tag it can still at least be heard. If you take away the alt tag, it can't be seen OR heard. – JP DeVries Mar 15 '16 at 16:15
  • 3
    @panzi I tested the solution and it seems like Chrome changed its behaviour. It won't render the broken image icon if `alt=""`. The same goes for Firefox. – Philipp Mitterer Dec 07 '18 at 10:42
-5

For future googlers, in 2016 there is a browser safe pure CSS way of hiding empty images using the attribute selector:

img[src="Error.src"] {
    display: none;
}

Edit: I'm back - for future googlers, in 2019 there is a way to style the actual alt text and alt text image in the Shadow Dom, but it only works in developer tools. So you can't use it. Sorry. It would be so nice.

#alttext-container {
    opacity: 0;
}
#alttext-image {
    opacity: 0;
}
#alttext {
    opacity: 0;
}
VerticalGrain
  • 564
  • 6
  • 9
  • 1
    `img[src=''] { display: none; }` This became relevant again with eBay html only templates – imos Jun 05 '17 at 06:34