Invert/change logo on scroll - html

An article over on askthecssguy.com shows how to change/invert an image on scroll using fixed backgrounds: http://askthecssguy.com/articles/mike-asks-the-css-guy-about-a-scrolling-trick-with-background-images/
My goal takes this concept further by having the image float over other elements (in this case images).
You can see the result here: http://playground.iamkeir.com/invert-logo/v2/
However, my implementation uses superfluous elements and, so, I was wondering if anyone had any ideas/suggestions of another way to achieve this?
Javascript is certainly an option but I worry it would not be lean/elegant. Someone also suggested using Canvas.
Any ideas welcomed! Thank you.

You can avoid extra markup by using :after CSS pseudo element. Thus, your final markup will look like:
<ul>
<li class="light">
<img src="http://farm3.static.flickr.com/2802/4253151258_7d12da9e1c_z.jpg" />
</li>
<li class="dark">
<img src="http://farm1.static.flickr.com/31/66005536_d1c5afca29_z.jpg?zz=1" />
</li>
<li class="light">
<img src="http://farm4.static.flickr.com/3574/3646151231_0c68f4f974_z.jpg" />
</li>
<li class="dark">
<img src="http://farm4.static.flickr.com/3432/3310214210_813d13c899_z.jpg" />
</li>
</ul>
And the altered CSS will be:
.dark:after,
.light:after,
.dark .after,
.light .after {
position: absolute;
display: block;
content: '';
top: 0; left: 0;
height: 100%;
width: 76px;
background: transparent url(logo-white.png) no-repeat fixed 0 0;
z-index: 5;
}
.dark:after,
.dark .after {
background-image: url(logo-black.png);
}
Notice that there is .after class there. This is to make it work in IE<8, which, sadly, requires to use an expression:
.dark,
.light {
behavior: expression( !this.before ? this.before = this.innerHTML = '<div class="after"></div>' + this.innerHTML : '' );
}
While using expressions is generally discouraged, this one shouldn't affect the performance too much, since it is fully evaluated only once, and when the element is created, the condition returns false.
There is one pitfall, though. If IE8 works in IE8/IE8 mode, the pseudo-elements will be under the images, unless you set negative z-index for the latter, which isn't always acceptable.
You can look at working example here.

what you're trying to do is totally possible using the current code you just need to use absolute positioning to move the content around. For example using the test page http://askthecssguy.com/examples/fixedBackgroundImages/example01.html you can modify the .header class and make it like this.
.header {
background: url("images/cuckoo_color.jpg") no-repeat fixed 20px 20px #DBDED1;
left: -151px;
padding: 40px 40px 40px 300px;
position: absolute;
}
Doing this will make the text float over the images. Going a step further instead of using a background image you could insert a transparent PNG into it's own DIV and float it over any position on the page and keep it's position fixed. You can checkout http://www.w3schools.com/css/css_positioning.asp for some examples.
Hope that helps!
Virgil

Related

By adding an image, my pseudo-element "::after" disappears. Why and how to fix? [duplicate]

I'm trying to use the :before selector to place an image over another image, but I'm finding that it simply doesn't work to place an image before an img element, only some other element. Specifically, my styles are:
.container
{
position: relative;
display: block;
}
.overlay:before
{
content: url(images/[someimage].png);
position: absolute;
left:-20px;
top: -20px;
}
and I find that this works fine:
<a href="[url]" class="container">
<span class="overlay"/>
<img width="200" src="[url]"/>
</a>
but this does not:
<a href="[url]" class="container">
<img width="200" src="[url]" class="overlay"/>
</a>
I can use a div or p element instead of that span, and the browser correctly overlays my image over the image in the img element, but if I apply the overlay class to the img itself, it doesn't work.
I'd like to get this working because that extra span offends me, but more importantly, I've got about 100 blog posts that I'd like to modify, and I can do this in one go if I could just modify the stylesheet, but if I have to go back and add an extra span element in between the a and img elements, this will be a lot more work.
Unfortunately, most browsers do not support using :after or :before on img tags.
http://lildude.co.uk/after-css-property-for-img-tag
However, it IS possible for you to accomplish what you need with JavaScript/jQuery. Check out this fiddle:
http://jsfiddle.net/xixonia/ahnGT/
$(function() {
$('.target').after('<img src="..." />');
});
Edit:
For the reason why this isn't supported, check out coreyward's answer.
The before and after pseudo-selectors don't insert HTML elements — they insert text before or after the existing content of the targeted element. Because image elements don't contain text or have descendants, neither img:before or img:after will do you any good. This is also the case for elements like <br> and <hr> for the same reason.
I found a way to make this work in pure css:
The I'm just fake content-method
a pure CSS method to enable img:after.
You can check out the CodePen: I'm just fake content or see the source.
Source & Snippet
img {
/* hide the default image */
height:0;
width:0;
/* hide fake content */
font-size:0;
color:transparent;
/* enable absolute position for pseudo elements */
position:relative;
/* and this is just fake content */
content:"I'm just fake content";
}
/* initial absolute position */
img:before,
img:after {
position:absolute;
top:0;
left:0;
}
/* img:before - chrome & others */
img:before {
content:url(http://placekitten.com/g/250/250);
}
/* img:before - firefox */
body:not(:-moz-handler-blocked) img:before {
padding:125px;
background:url(http://placekitten.com/g/250/250) no-repeat;
}
/* img:after */
img:after {
/* width of img:before */
left:250px;
content:url(http://lorempixel.com/350/200/city/1);
}
<img
alt="You are watching the ~ I'm just fake content ~ method"
/>
Browser support
✓ Chrome 10+
✓ Firefox 11+
✓ Opera 9.8+
✓ Safari
No support
⊗ Internet Explorer 8 / 9
Please test in other browsers
Due to the nature of <img> being a replaced element, document styling doesn’t affected it.
To reference it anyway, <picture> provides an ideal, native wrapper that can have pseudo-elements attached to it, like so:
img::after,
picture::after{
content:"\1F63B";
font-size:larger;
margin:-1em;
}
<img src="//placekitten.com/110/80">
<picture>
<img src="//placekitten.com/110/80">
</picture>
Here's another solution using a div container for img while using :hover::after to achieve the effect.
The HTML as follows:
<div id=img_container><img src='' style='height:300px; width:300px;'></img></div>
The CSS as follows:
#img_container {
margin:0;
position:relative;
}
#img_container:hover::after {
content:'';
display:block;
position:absolute;
width:300px;
height:300px;
background:url('');
z-index:1;
top:0;
}
To see it in action, check out the fiddle I've created. Just so you know this is cross browser friendly and there's no need to trick the code with 'fake content'.
The pseudo-elements generated by ::before and ::after are contained by the element's formatting box, and thus don't apply to replaced elements such as img, or to br elements.
https://developer.mozilla.org/en-US/docs/Web/CSS/::after
I think the best way to look at why this doesn't work is that :before and :after insert their content before or after the content within the tag you're applying them to. So it works with divs or spans (or most other tags) because you can put content inside them.
<div>
:before
Content
:after
</div>
However, an img is a self-contained, self-closing tag, and since it has no separate closing tag, you can't put anything inside of it. (That would need to look like <img>Content</img>, but of course that doesn't work.)
I know this is an old topic, but it pops up first on Google, so hopefully this will help others learn.
This one works for me:
html
<ul>
<li> name here </li>
</ul>
CSS
ul li::before {
content: url(../images/check.png);
}
::after may be used to display the fallback image of an image
See the example below, first 2 img tags are point to the broken urls. But the second one displays the fallback image instead of the default broken logo from the browser. However, I'm not sure this's any practical, I find it kind of tricky to get it to work right.
img {
position: relative;
display: inline-block;
width: 300px;
height: 200px;
vertical-align: top;
}
img:not(:first-child)::after {
position: absolute;
left: 0; top: 0; right: 0; bottom: 0;
content: "<" attr(alt) "> NOT FOUND";
border: 1px dashed #999;
background: url(https://cdn.dribbble.com/users/1012566/screenshots/4187820/topic-2.jpg) center/100%;
}
<img src="https://source.unsplash.com/random/100/75" alt="logo">
<img src="https://source.unsplash.com/random/100/75" alt="logo">
<img src="https://source.unsplash.com/random/100x75" alt="logo">
In these cases it is preferable to use the <figure> tag, which allows you to manage the css in an optimal way
This way you can use after just on the figure
Example
<div class="exemple">
<figure>
<img src="img1.jpg"/>
</figure>
<figure>
<img src="img2.jpg"/>
</figure>
</div>
<img> is a replaced element and using :before or :after pseudo-elements on it works if the image fails to load and otherwise it does not work. If you intend to have a fallback in case of image load failure,please refer to https://stackoverflow.com/a/71478688/14204452
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<style>
#image img{
display: inline-block;
max-width: 50%;
}
#image::after {
position: absolute;
top: 0;
content: url('https://img.icons8.com/plasticine/100/000000/about.png');
}
</style>
<title>img before</title>
</head>
<body>
<a id="image" href="">
<img src="https://static.remove.bg/remove-bg-web/5c20d2ecc9ddb1b6c85540a333ec65e2c616dbbd/assets/start-1abfb4fe2980eabfbbaaa4365a0692539f7cd2725f324f904565a9a744f8e214.jpg">
</a>
</body>
</html>
Try this code
.button:after {
content: ""
position: absolute
width: 70px
background-image: url('../../images/frontapp/mid-icon.svg')
display: inline-block
background-size: contain
background-repeat: no-repeat
right: 0
bottom: 0
}
I tried and found a simpler method to do so. Here is the HTML:
<img id="message_icon" src="messages2.png">
<p id="empty_para"></p>
What I did was place an empty <p> tag after my image tag. Now I will use p::before to show the image and position it according to my needs. Here is the CSS:
#empty_para
{
display:inline;
font-size:40;
background:orange;
border:2px solid red;
position:relative;
top:-400px;
left:100px;
}
#empty_para::before
{
content: url('messages.png');
}
Try it.
Try ::after on previous element.
Just give the Image "position: relative" and it will work

Hoverable imagery

I have a scenario in which I have a team page with pictures and some blurb. Under each picture I have social media links much like the following:
These are images that sit within a horizontal list underneath each item using the below base markup.
<ul>
<li>
<a><img src=""/></a>
</li>
<li>
<a><img src=""/></a>
</li>
</ul>
At the moment these are images but I would very much like if when hovered the grey inards of these images turned blue.
I was thinking just have a span with a background image like this:
<a><span class="linkedin"></span></a>
.linkedin{
height:28px;
width:auto;
background-image:url(link/to/the/linkedin/picture)
}
.linkedin:hover{
height:28px;
width:auto;
background-image:url(link/to/the/linkedin/picture-blue-version)
}
However, when I attempted this the space was empty instead of taking the size of the image.
If I enter as content I get a small part of the background image, furthermore giving the class an absolute position takes it out of document flos
Is this the ideal approach?
The problem is if you use a <span> element you need to set it to display: inline-block and you need to set a width for the image to show up. Then it works, here is a demo:
.linkedin {
display: inline-block;
width: 140px;
height:100px;
background-image:url(http://ipsumimage.appspot.com/140x100,ff7700)
}
.linkedin:hover {
background-image:url(http://ipsumimage.appspot.com/140x100,0000FF)
}
<span class="linkedin"></span>
As you see on the first :hover it flickers. Cause it will not load the image bevore you :hover the first time. This is why you should consider another solution. Like mentioned in some comments you could use http://fontawesome.io/icons/ and then just change the color.
To prevent flickering you could do the same with using <img> tags then the source will be loaded and ready to be shown on :hover. But it works best with also setting positions, demo like so:
a.special {
position: relative;
}
a.special img {
visibility: hidden;
position: absolute;
top: 0;
left: 0;
}
a.special img:first-child {
visibility: visible;
}
a.special:hover img:first-child {
visibility: hidden;
}
a.special:hover img:last-child {
visibility: visible;
}
<a class="special" href="#">
<img src="http://ipsumimage.appspot.com/140x100,ff7700">
<img src="http://ipsumimage.appspot.com/140x100,0000FF">
</a>
Best approach for this is to use SVG's and change the fill of the SVG on hover.
Your approach should work however, it might be that you've not got the correct size image? try 'background-size: cover;' Or that the element has no width. Try setting a width on the span too. (don't forget to give it 'display: inline-block;' too.
Ed: checkout https://css-tricks.com/lodge/svg/
Font-Awesome is a great idea for what you're trying to achieve. Takes less data to load the page too if you can get away with using text in place of images.
By the way, when using the :hover property there is no need to redefine the width and height of the image... Just redefine the changes you'd like to make.

How to center an image, make it act as an link and have an mouseover command?

So, I'm really, really a noob when it comes to HTML/CSS, so I apologize already.
So, what I need to do, is center an image (so that it's centered also at different resolutions/screens), on mouseover change the image to another source, and also make it act as a link to another web page.
At HTML I have this:
<a href="url to the webpage">
<img class="Logo" src="Logo.png">
</a>
And at CSS I have this:
img.Logo{
position: absolute;
margin: auto;
left: 0;
right: 0;
top: 0;
bottom: 0;
}
So I have it nicely centered and acting as a link too, but I have absolutely no freaking idea how to make it show another image on mouseover. I'm sorry if this has been asked before or if this is a really simple question, I tried googling it out but none gave me an answer that's simple enough for me. :|
use the css if you don't have position: absolute-
img {
margin: 0 auto;
}
if you want to apply position: absolute then use this css-
img {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%); /* make sure to add all the vendor prefixes */
}
for the mouseover effect use this JS-
document.getElementsByClassName('Logo')[0].onmouseover = function() {
this.src = 'yourAnotherImgUrl';
}
if you want to revert back to the image when mouse is out then use this JS -
document.getElementsByClassName('Logo')[0].onmouseout = function() {
this.src = 'yourOriginalImgUrl';
}
<a href="url to the webpage">
<img src="Logo.png" onmouseover="this.src='your_other_image'"
onmouseout="this.src='Logo.png'" />
</a>
Using JavaScript you can have the default image displayed before the onmousehover event changes the image to a second image, then back to the original upon the onmouseout event being triggered.

Change image size within a division

I have a division placed on the bottom of the page. I put an image into this division, but I don't know how to modify the image. The problem may be, that the inline style for <img> is setting modification rules for all images. I have an inline style sheet that has this code and HTML code for <div>.
My CSS code looks like this:
<style type="text/css">
img {
image-align: center;
padding: 10px;
height: 200px;
width: 140px;
}
div {
position: absolute;
right: 10px;
}
</style>
And my HTML code is like that:
<div align="center" >
<img src="images/music_banner.jpg" >
</div>
you can do this:
div img{
}
or give the div a name and do this
#div img{
}
or you give the img an id as below
<div>
<img id="mg"/>
</div>
Use id as #mg in CSS code.
or you can do as define class name in img tag.
<div>
<img class="mg"/>
</div>
Use class as .mg in CSS Code.
You might try learning a little bit more about CSS selectors: these are the rules that tell the browser which element you'd like to apply the following rules to.
I would recommend Code Academy for an easy to follow course. You can skip down to the CSS section if you are already comfortable with HTML.
Note: if you google CSS, you'll get "w3schools" as the first results. That website is generally derided on Stack Overflow. I don't know if it's really that bad, but I tend to skip it just because everyone else has a bad opinion of it. Your call if you find it helpful of course.
I should note that I like to use the W3C (World Wide Web Consortium) website for reference, as they're the ones trying to make everything standard. It is a pretty technical read, though.
Create a div element in your HTML code:
<div class="parent">
<img src="image">
</div>
Than add this to your CSS code:
.parent {
width: 42px; /* I took the width from your post and placed it in css */
height: 42px;
}
/* This will style any <img> element in .parent div */
.parent img {
height: 100%;
width: 100%;
}

How to hide image broken Icon using only CSS/HTML?

How can I hide the broken image icon?
Example:
I have an image with error src:
<img src="Error.src"/>
The solution must work in all browsers.
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.
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
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">
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"/>
If you will not add alt it will show the show corrupt thumbnail
<img src="pic_trulli.jpg"/>
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/
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.
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;
}
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>
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.
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.
The same idea as described by others works in React as follow:
<img src='YOUR-URL' onError={(e) => e.target.style.display='none' }/>
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
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">
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:
A broken image without alt attribute (baseline): show a broken image
A broken image with alt text (baseline): show the alt text
A broken image with empty alt text (baseline): show the alt text (nothing)
A broken image with alt text (our CSS): hide the broken image
A broken image with empty alt text (our CSS): show the alt text (nothing)
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.
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.
The trick with img::after is a good stuff, but has at least 2 downsides:
not supported by all browsers (e.g. doesn't work on Edge https://codepen.io/dsheiko/pen/VgYErm)
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;
}
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();
}
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.
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>`;"/>
Angular way of hiding the broken image.
Inside Html file
<img *ngIf="showImage" [src]="url" (error)="showImage = false">
Inside Ts file
public showImage = true;
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.
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>
Hide image alt with this
img {
color: transparent;
}
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! ;)
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;
}