Related
Is it possible to set the src attribute value in CSS?
In most cases, we use it like this:
<img src="pathTo/myImage.jpg" />
and I want it to be something like this
<img class="myClass" />
.myClass {
some-src-property: url("pathTo/myImage.jpg");
}
I want to know if there is a way doing it without using the background or background-image properties in CSS.
Use content:url("image.jpg").
Full working solution (Live Demo):
<!doctype html>
<style>
.MyClass123{
content:url("http://imgur.com/SZ8Cm.jpg");
}
</style>
<img class="MyClass123"/>
Tested and working:
Chrome 14.0.835.163
Safari 4.0.5
Opera 10.6
Firefox 100 & newer
Tested and Not working:
FireFox 40.0.2 (observing Developer Network Tools, you can see that the URL loads, but the image is not displayed)
Internet Explorer 11.0.9600.17905 (URL never loads)
There is a solution that I found out today (works in IE6+, FF, Opera, Chrome):
<img src='willbehidden.png'
style="width:0px; height:0px; padding: 8px; background: url(newimage.png);">
How it works:
The image is shrunk until no longer visible by the width & height.
Then, you need to 'reset' the image size with padding. This
one gives a 16x16 image. Of course you can use padding-left /
padding-top to make rectangular images.
Finally, the new image is put there using background.
If the new background image is too large or too small, I recommend using background-size for example: background-size:cover; which fits your image into the allotted space.
It also works for submit-input-images, they stay clickable.
See live demo: http://www.audenaerde.org/csstricks.html#imagereplacecss
Enjoy!
A collection of possible methods to set images from CSS
CSS2's :after pseudo-element or the newer syntax ::after from CSS3 along with the content: property:
First W3C Recommendation: Cascading Style Sheets, level 2
CSS2 Specification 12 May 1998
Latest W3C Recommendation: Selectors Level 3
W3C Recommendation 29 September 2011
This method appends content just after an element's document tree content.
Note: some browsers experimentally render the content property directly over some element selectors disregarding even the latest W3C recommendation that defines:
Applies to: :before and :after pseudo-elements
CSS2 syntax (forward-compatible):
.myClass:after {
content: url("somepicture.jpg");
}
CSS3 Selector:
.myClass::after {
content: url("somepicture.jpg");
}
Default rendering: Original Size (does not depend on explicit size declaration)
This specification does not fully define the interaction of :before and :after with replaced elements (such as IMG in HTML). This will be defined in more detail in a future specification.
but even at the time of this writing, behaviour with a <IMG> tag is still not defined and although it can be used in a hacked and non standards compliant way, usage with <img> is not recommended!
Great candidate method, see conclusions...
**CSS1**'s [`background-image:`](http://www.w3.org/TR/REC-CSS1-961217#background-image) property:
First W3C Recommendation: Cascading Style Sheets, level 1 17 Dec 1996
This property sets the background image of an element. When setting a background image, one should also set a background color that will be used when the image is unavailable. When the image is available, it is overlaid on top of the background color.
This property has been around from the beginning of CSS and nevertheless it deserve a glorious mention.
Default rendering: Original Size (cannot be scaled, only positioned)
However,
CSS3's background-size: property improved on it by allowing multiple scaling options:
Latest W3C Status: Candidate Recommendation CSS Backgrounds and Borders Module Level 3 9 September 2014
[length> | <percentage> | auto ]{1,2} | cover | contain
But even with this property, it depends on container size.
Still a good candidate method, see conclusions...
CSS2's list-style: property along with display: list-item:
First W3C Recommendation: Cascading Style Sheets, level 2
CSS2 Specification 12 May 1998
list-style-image: property sets the image that will be used as the list item marker (bullet)
The list properties describe basic visual formatting of lists: they allow style sheets to specify the marker type (image, glyph, or number)
display: list-item — This value causes an element (e.g., <li> in HTML) to generate a principal block box and a marker box.
.myClass {
display: list-item;
list-style-position: inside;
list-style-image: url("someimage.jpg");
}
Shorthand CSS: (<list-style-type> <list-style-position> <list-style-image>)
.myClass {
display: list-item;
list-style: square inside url("someimage.jpg");
}
Default rendering: Original Size (does not depend on explicit size declaration)
Restrictions:
-
Inheritance will transfer the 'list-style' values from OL and UL elements to LI elements. This is the recommended way to specify list style information.
They do not allow authors to specify distinct style (colors, fonts, alignment, etc.) for the list marker or adjust its position
This method is also not suitable for the <img> tag as the conversion cannot be made between element types, and here's the limited, non compliant hack that doesn't work on Chrome.
Good candidate method, see conclusions...
CSS3's border-image: property recommendation:
Latest W3C Status: Candidate Recommendation CSS Backgrounds and Borders Module Level 3 9 September 2014
A background-type method that relies on specifying sizes in a rather peculiar manner (not defined for this use case) and fallback border properties so far (eg. border: solid):
Note that, even though they never cause a scrolling mechanism, outset
images may still be clipped by an ancestor or by the viewport.
This example illustrates the image being composed only as a bottom-right corner decoration:
.myClass {
border: solid;
border-width: 0 480px 320px 0;
border-image: url("http://i.imgur.com/uKnMvyp.jpg") 0 100% 100% 0;
}
Applies to: All elements, except internal table elements when border-collapse: collapse
Still it can't change an <img>'s tag src (but here's a hack), instead we can decorate it:
.myClass {
border: solid;
border-width: 0 96px 96px 0;
border-image: url("http://upload.wikimedia.org/wikipedia/commons/9/95/Christmas_bell_icon_1.png")
0 100% 100% 0;
}
<img width="300" height="120"
src="http://fc03.deviantart.net/fs71/f/2012/253/b/0/merry_christmas_card_by_designworldwide-d5e9746.jpg"
class="myClass"
Good candidate method to be considered after standards propagate.
CSS3's element() notation working draft is worth a mention also:
Note: The element() function only reproduces the appearance of the referenced element, not the actual content and its structure.
<div id="img1"></div>
<img id="pic1" src="http://i.imgur.com/uKnMvyp.jpg" class="hide" alt="wolf">
<img id="pic2" src="http://i.imgur.com/TOUfCfL.jpg" class="hide" alt="cat">
We'll use the rendered contents of one of the two hidden images to change the image background in #img1 based on the ID Selector via CSS:
#img1 {
width: 480px;
height: 320px;
background: -moz-element(#pic1) no-repeat;
background-size: 100% 100%;
}
.hide {display: none}
Notes: It's experimental and only works with the -moz prefix in Firefox and only over background or background-image properties, also needs sizes specified.
element() Live Demo
Conclusions
Any semantic content or structural information goes in HTML.
Styling and presentational information goes in CSS.
For SEO purposes, don't hide meaningful images in CSS.
Background graphics are usually disabled when printing.
Custom tags could be used and styled from CSS, but primitive versions of Internet Explorer do not understand](IE not styling HTML5 tags (with shiv)) without Javascript or CSS guidance.
SPA's (Single Page Applications), by design, usually incorporate images in the background
Having said that, let's explore HTML tags fit for image display:
The <li> element [HTML4.01+]
Perfect usecase of the list-style-image with display: list-item method.
The <li> element, can be empty, allows flow content and it's even permitted to omit the </li> end tag.
.bulletPics > li {display: list-item}
#img1 {list-style: square inside url("http://upload.wikimedia.org/wikipedia/commons/4/4d/Nuvola_erotic.png")}
#img2 {list-style: square inside url("http://upload.wikimedia.org/wikipedia/commons/7/74/Globe_icon_2014-06-26_22-09.png")}
#img3 {list-style: square inside url("http://upload.wikimedia.org/wikipedia/commons/c/c4/Kiwi_fruit.jpg")}
<ul class="bulletPics">
<li id="img1">movie</li>
<li id="img2">earth</li>
<li id="img3">kiwi</li>
</ul>
Limitations: hard to style (width: or float: might help)
The <figure> element [HTML5+]
The figure element represents some flow content, optionally with a caption, that is self-contained (like a complete sentence) and is typically referenced as a single unit from the main flow of the document.
The element is valid with no content, but is recommended to contain a <figcaption>.
The element can thus be used to annotate illustrations, diagrams, photos, code listings, etc.
Default rendering: the element is right aligned, with both left and right padding!
FIGURE Live Demo
The <object> element [HTML4+]
To include images, authors may use the OBJECT element or the IMG element.
The data attribute is required and can have a valid MIME type as a value!
<object data="data:x-image/x,"></object>
Note: a trick to make use of the <object> tag from CSS would be to set a custom valid MimeType x-image/x followed by no data (value has no data after the required comma ,)
Default rendering: 300 x 150px, but size can be specified either in HTML or CSS.
OBJECT Live Demo
The <SVG> tag
Needs a SVG capable browser and has a <image> element for raster images
SVG Live Demo
The <canvas> element [HTML5+].
The width attribute defaults to 300, and the height attribute defaults to 150.
CANVAS Live Demo
The <input> element with type="image"
Limitations:
... the element is expected to appear button-like to indicate that the element is a button.
which Chrome follows and renders a 4x4px empty square when no text
Partial solution, set value=" ":
<input type="image" id="img1" value=" ">
INPUT type=image Live Demo
Also watch out for the upcoming <picture> element in HTML5.1, currently a working draft.
i used the empty div solution, with this CSS:
#throbber {
background-image: url(/Content/pictures/ajax-loader.gif);
background-repeat: no-repeat;
width: 48px;
height: 48px;
min-width: 48px;
min-height: 48px;
}
HTML:
<div id="throbber"></div>
I found a better way than the proposed solutions, but it does use the background-image indeed.
Compliant method (cannot confirm for IE6)
Credits: http://www.kryogenix.org/code/browser/lir/
<img src="pathTo/myImage.jpg"/>
The CSS:
img[src*="pathTo/myImage.jpg"] {
background-image: url("mynewimg.jpg"); /* lets say 20x20 */
width: 20px;
display:inline-block;
padding: 20px 0 0 0;
height: 0px !important;
/* for IE 5.5's bad box model */
height /**/:20px;
}
The old image is not seen and the new is seen as expected.
The following neat solution only works for webkit
img[src*="pathTo/myImage.jpg"] {
/* note :) */
content:'';
display:inline-block;
width: 20px;
height: 20px;
background-image: url("mynewimg.jpg"); /* lets say 20x20 */
}
They are right. IMG is a content element and CSS is about design.
But, how about when you use some content elements or properties for design purposes?
I have IMG across my web pages that must change if i change the style (the CSS).
Well this is a solution for defining IMG presentation (no really the image) in CSS style.
create a 1x1 transparent gif or png.
Assign propery "src" of IMG to that image.
Define final presentation with "background-image" in the CSS style.
It works like a charm :)
Here is a very good solution -> http://css-tricks.com/replace-the-image-in-an-img-with-css/
Pro(s) and Con(s):
(+) works with vector image that have relative width/height (a thing that RobAu's answer does not handle)
(+) is cross browser (works also for IE8+)
(+) it only uses CSS. So no need to modify the img src (or if you do not have access/do not want to change the already existing img src attribute).
(-) sorry, it does use the background css attribute :)
No you can't set the image src attribute via CSS. The closest you can get is, as you say, background or background-image. I wouldn't recommend doing that anyway as it would be somewhat illogical.
However, there is a CSS3 solution available to you, if the browsers you're targeting are able to use it. Use content:url as described in Pacerier's answer. You can find other, cross-browser solutions in the other answers below.
You can define 2 images in your HTML code and use display: none; to decide which one will be visible.
Put several images in a "controlling" container, and change the container's class instead. In CSS, add rules to manage images' visibility depending on the container's class. This will produce the same effect as changing img src property of a a single image.
HTML:
<span id="light" class="red">
<img class="red" src="red.png" />
<img class="yellow" src="yellow.png" />
<img class="green" src="green.png" />
</span>
CSS:
#light { ... }
#light * { display: none; } // all images are hidden
#light.red .red { display: inline; } // show red image when #light is red
#light.yellow .yellow { display: inline; } // .. or yellow
#light.green .green { display: inline; } // .. or green
Note that it will preload all images, like with CSS backround-images, but unlike changing img src via JS.
Some data I would leave in HTML, but it is better to define the src in CSS:
<img alt="Test Alt text" title="Title text" class="logo">
.logo {
content:url('../images/logo.png');
}
Or you could do this which I found on the interweb thingy.
https://robau.wordpress.com/2012/04/20/override-image-src-in-css/
<img src="linkToImage.jpg" class="egg">
.egg {
width: 100%;
height: 0;
padding: 0 0 200px 0;
background-image: url(linkToImage.jpg);
background-size: cover;
}
So effectively hiding the image and padding down the background. Oh what a hack but if you want an IMG tag with alt text and a background that can scale without using JavaScript?
In a project I'm working on now I created a hero block twig template
<div class="hero">
<img class="image" src="{{ bgImageSrc }}"
alt="{{ altText }}" style="background-image: url({{ bgImageSrc }});">
</div>
Alternative way
.myClass {
background: url('/img/loading_big.gif');
}
<div class="myClass"></div>
As far as I am aware of, YOU CANNOT. CSS is about style and image's src is content.
To reiterate a prior solution and to stress the pure CSS implementation here is my answer.
A Pure CSS solution is needed in cases where you are sourcing content from another site, and thus you have no control over the HTML that is delivered. In my case I am trying to remove branding of licensed source content so that the licencee does not have to advertise for the company they are buying the content from. Therefore, I'm removing their logo while keeping everything else. I should note that this is within my client's contract to do so.
{ /* image size is 204x30 */
width:0;
height:0;
padding-left:102px;
padding-right:102px;
padding-top:15px;
padding-bottom:15px;
background-image:url(http://sthstest/Style%20Library/StThomas/images/rhn_nav_logo2.gif);
}
I know this is a really old question however no answers provide the proper reasoning for why this can never be done. While you can "do" what you are looking for you cannot do it in a valid way. In order to have a valid img tag it must have the src and alt attributes.
So any of the answers giving a way to do this with an img tag that does not use the src attribute are promoting use of invalid code.
In short: what you are looking for cannot be done legally within the structure of the syntax.
Source: W3 Validator
If you don't want to set a background property then you can't set the src attribute of an image using only CSS.
Alternatively you can use JavaScript to do such a thing.
Using CSS, it can't be done. But, if you are using JQuery, something like this will do the trick:
$("img.myClass").attr("src", "http://somwhere");
You can convert it with JS:
$('.image-class').each(function(){
var processing = $(this).attr('src');
$(this).parent().css({'background-image':'url('+processing+')'});
$(this).hide();
});
If you are trying to add an image in a button dynamically based on the context of your project, you can use the ? take to reference the source based on an outcome. Here I am using mvvm design to let my Model.Phases[0] value determine whether I want my button to be populated with images of a lightbulb on or off based on the value of the light phase.
Not sure if this helps. I'm using JqueryUI, Blueprint, and CSS. The class definition should allow you to style the button based on whatever you'd like.
<button>
<img class="#(Model.Phases[0] ? "light-on": "light-off")" src="#(Model.Phases[0] ? "~/Images/LightBulbOn.png" : "~/Images/LightBulbOff.png")"/>
<img class="#(Model.Phases[0] ? "light-on": "light-off")" src="#(Model.Phases[0] ? "~/Images/LightBulbOn.png" : "~/Images/LightBulbOff.png")"/>
<img class="#(Model.Phases[0] ? "light-on": "light-off")" src="#(Model.Phases[0] ? "~/Images/LightBulbOn.png" : "~/Images/LightBulbOff.png")"/>
I would add this: background image could be also positioned with background-position: x y; (x horizontal y vertical). (..)
My case, CSS:
(..)
#header {
height: 100px;
background-image: url(http://.../head6.jpg);
background-position: center;
background-repeat: no-repeat;
background-color: grey;
(..)
}
(...)
HTMl Code:
<!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="css destination" />
</head>
<body>
<!-- click-able pic with link -->
<a href="site you want">
<!-- Take the off if you don't want click-able link -->
<h1 id(or class)="nameOfClassorid">
<span>Text that is not important</span>
</h1>
</a>
</body>
</html>
Css Code:
span {
display: none;
}
h1 id or class {
height: of pic;
width: of pic;
/* Only flaw (so far) read bottom */
background-image:url(/* "image destination" */);
}
h1 id or class:hover {
/* Now the awesome part */
background-image:url(/* 'new background!!!' */);
}
I've been studying html after school for a few days, and wanted to know how to do this. Found out the background and then put 2 and 2 together.
This works 100% I checked, if not make sure you fill in necessary things!!!
We need to specify height, because without it there would be nothing!!!
I'll leave this basic shell you can add-on.
Example:
<!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="style.css" />
</head>
<body>
<a href="http:localhost">
<h1>
<span>Text that is not important</span>
</h1>
</a>
</body>
</html>
span {
display: none;
}
h1 {
height: 100px;
width: 100px;
background-image:url("http://linuxlog.org/wp-content/uploads/2011/01/Ubuntu-Desktop-#-2011-01-11-191526-300x225.png");
}
h1:hover {
height: 300px;
width: 300px;
background-image:url("http://cdn.css-tricks.com/images/ads/wufoo-600x600-red.png");
}
P.S. Yes I am a Linux user ;)
Any method based on background or background-image is likely to fail when user prints the document with "print background colors and images" disabled.
Which is unfortunately typical browser's default.
The only print-friendly and cross-browser compatible method here is the one proposed by Bronx.
Just use HTML5 :)
<picture>
<source srcset="smaller.jpg" media="(max-width: 768px)">
<source srcset="default.jpg">
<img srcset="default.jpg" alt="My default image">
</picture>
I use bootstrap 3. I try to use "icon link" by using tag <a> as shown below:
HTML:
CSS:
.link {
background-image: url(img/icon.png);
}
It is important to say, that my stylesheet is in "main folder", that is in folder, where is a img folder with icon.png file. So it seems wrong url is not the case.
I can't figure out why image is not showing.
The anchor element has no content, and it has no styles that would affect it's dimensions, consequently it has an effective area of zero square pixels.
The background image is probably being applied just fine, you can't see it because there is no area on which it can be displayed.
The code implies that the image is there to tell the visitor where the link goes, that would mean that the image is content and not background and should be expressed as an image element (which would take on the dimensions of the image file automatically).
Using an image element also provides you with the opportunity to supply alt text for the benefit of screen readers / search engines / people with internet connections that briefly fell over while loading the image / etc.
<img src="img/icon.png" alt="top of page">
Because your is empty.
You need to give it a size :
.link {
background-image: url(img/icon.png);
height:100px;
width:100px;
display:block;
}
You have to make the tag enought big to show the image
Example:
CSS:
.link {
background-image: url(img/icon.png);
display: block;
width: 100px;
height: 100px;
}
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;
}
I have the following html:
<div class="A">
<img src="image1.png" width="100px" height="100px"/>
</div>
In my media queries css style sheet, I would like to replace that image with another one (image2.png).
What is the css code I need to write?
I tried the following:
.A img
{
background:url("image2.png") no-repeat;
}
But this doesn't seem correct?
If you are using CSS3, then content is the answer:
.A img
{
content: url("image2.png");
}
You can't modify that in CSS, instead, use a div like this:
<div id='#theImage'></div>
Then in CSS:
#theImage {
width:100px;
height:100px;
background:url("image1.png") no-repeat;
}
Then you can restyle the div using a media query.
Your code doesn't work because the image in the original <img> tag is a foreground image, which is different from a background image.
So setting the CSS doesn't get rid of the original image. And in addition, although the CSS does work, the background image it displays is shown behind the foreground image.
In order to do this, you need to either have the original image as a background image (ie set using CSS background-image property), or switch to replacing the foreground image in your script. This would involve setting the src attribute:
$('.a img').attr('src','newimage.png');
you're setting a background of an img element you won't be able to see, because the image defined in its src attribute is covering it
Anyway if both the images are relevant for the context from a semantic point of view, you should not use css to place the second image in place of the first one
If you put background on an image, the image will simply overlap the background; making the background totally invisible.
The solution is to make the image as a background of an element
Like so: http://jsfiddle.net/PabXF/
.image-replacement {
display: block;
-moz-box-sizing: border-box;
box-sizing: border-box;
background: url(https://www.whatsappimages.in/wp-content/uploads/2021/07/Top-HD-sad-quotes-for-whatsapp-status-in-hindi-Pics-Images-Download-Free.gif)
no-repeat;
width: 180px;
height: 236px;
padding-left: 180px;
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h2>Image replaced with Image</h2>
<img class="image-replacement" src="https://images.unsplash.com/photo-1503023345310-bd7c1de61c7d?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8aHVtYW58ZW58MHx8MHx8&w=1000&q=80" />
</body>
</html>
Is it possible to set the src attribute value in CSS?
In most cases, we use it like this:
<img src="pathTo/myImage.jpg" />
and I want it to be something like this
<img class="myClass" />
.myClass {
some-src-property: url("pathTo/myImage.jpg");
}
I want to know if there is a way doing it without using the background or background-image properties in CSS.
Use content:url("image.jpg").
Full working solution (Live Demo):
<!doctype html>
<style>
.MyClass123{
content:url("http://imgur.com/SZ8Cm.jpg");
}
</style>
<img class="MyClass123"/>
Tested and working:
Chrome 14.0.835.163
Safari 4.0.5
Opera 10.6
Firefox 100 & newer
Tested and Not working:
FireFox 40.0.2 (observing Developer Network Tools, you can see that the URL loads, but the image is not displayed)
Internet Explorer 11.0.9600.17905 (URL never loads)
There is a solution that I found out today (works in IE6+, FF, Opera, Chrome):
<img src='willbehidden.png'
style="width:0px; height:0px; padding: 8px; background: url(newimage.png);">
How it works:
The image is shrunk until no longer visible by the width & height.
Then, you need to 'reset' the image size with padding. This
one gives a 16x16 image. Of course you can use padding-left /
padding-top to make rectangular images.
Finally, the new image is put there using background.
If the new background image is too large or too small, I recommend using background-size for example: background-size:cover; which fits your image into the allotted space.
It also works for submit-input-images, they stay clickable.
See live demo: http://www.audenaerde.org/csstricks.html#imagereplacecss
Enjoy!
A collection of possible methods to set images from CSS
CSS2's :after pseudo-element or the newer syntax ::after from CSS3 along with the content: property:
First W3C Recommendation: Cascading Style Sheets, level 2
CSS2 Specification 12 May 1998
Latest W3C Recommendation: Selectors Level 3
W3C Recommendation 29 September 2011
This method appends content just after an element's document tree content.
Note: some browsers experimentally render the content property directly over some element selectors disregarding even the latest W3C recommendation that defines:
Applies to: :before and :after pseudo-elements
CSS2 syntax (forward-compatible):
.myClass:after {
content: url("somepicture.jpg");
}
CSS3 Selector:
.myClass::after {
content: url("somepicture.jpg");
}
Default rendering: Original Size (does not depend on explicit size declaration)
This specification does not fully define the interaction of :before and :after with replaced elements (such as IMG in HTML). This will be defined in more detail in a future specification.
but even at the time of this writing, behaviour with a <IMG> tag is still not defined and although it can be used in a hacked and non standards compliant way, usage with <img> is not recommended!
Great candidate method, see conclusions...
**CSS1**'s [`background-image:`](http://www.w3.org/TR/REC-CSS1-961217#background-image) property:
First W3C Recommendation: Cascading Style Sheets, level 1 17 Dec 1996
This property sets the background image of an element. When setting a background image, one should also set a background color that will be used when the image is unavailable. When the image is available, it is overlaid on top of the background color.
This property has been around from the beginning of CSS and nevertheless it deserve a glorious mention.
Default rendering: Original Size (cannot be scaled, only positioned)
However,
CSS3's background-size: property improved on it by allowing multiple scaling options:
Latest W3C Status: Candidate Recommendation CSS Backgrounds and Borders Module Level 3 9 September 2014
[length> | <percentage> | auto ]{1,2} | cover | contain
But even with this property, it depends on container size.
Still a good candidate method, see conclusions...
CSS2's list-style: property along with display: list-item:
First W3C Recommendation: Cascading Style Sheets, level 2
CSS2 Specification 12 May 1998
list-style-image: property sets the image that will be used as the list item marker (bullet)
The list properties describe basic visual formatting of lists: they allow style sheets to specify the marker type (image, glyph, or number)
display: list-item — This value causes an element (e.g., <li> in HTML) to generate a principal block box and a marker box.
.myClass {
display: list-item;
list-style-position: inside;
list-style-image: url("someimage.jpg");
}
Shorthand CSS: (<list-style-type> <list-style-position> <list-style-image>)
.myClass {
display: list-item;
list-style: square inside url("someimage.jpg");
}
Default rendering: Original Size (does not depend on explicit size declaration)
Restrictions:
-
Inheritance will transfer the 'list-style' values from OL and UL elements to LI elements. This is the recommended way to specify list style information.
They do not allow authors to specify distinct style (colors, fonts, alignment, etc.) for the list marker or adjust its position
This method is also not suitable for the <img> tag as the conversion cannot be made between element types, and here's the limited, non compliant hack that doesn't work on Chrome.
Good candidate method, see conclusions...
CSS3's border-image: property recommendation:
Latest W3C Status: Candidate Recommendation CSS Backgrounds and Borders Module Level 3 9 September 2014
A background-type method that relies on specifying sizes in a rather peculiar manner (not defined for this use case) and fallback border properties so far (eg. border: solid):
Note that, even though they never cause a scrolling mechanism, outset
images may still be clipped by an ancestor or by the viewport.
This example illustrates the image being composed only as a bottom-right corner decoration:
.myClass {
border: solid;
border-width: 0 480px 320px 0;
border-image: url("http://i.imgur.com/uKnMvyp.jpg") 0 100% 100% 0;
}
Applies to: All elements, except internal table elements when border-collapse: collapse
Still it can't change an <img>'s tag src (but here's a hack), instead we can decorate it:
.myClass {
border: solid;
border-width: 0 96px 96px 0;
border-image: url("http://upload.wikimedia.org/wikipedia/commons/9/95/Christmas_bell_icon_1.png")
0 100% 100% 0;
}
<img width="300" height="120"
src="http://fc03.deviantart.net/fs71/f/2012/253/b/0/merry_christmas_card_by_designworldwide-d5e9746.jpg"
class="myClass"
Good candidate method to be considered after standards propagate.
CSS3's element() notation working draft is worth a mention also:
Note: The element() function only reproduces the appearance of the referenced element, not the actual content and its structure.
<div id="img1"></div>
<img id="pic1" src="http://i.imgur.com/uKnMvyp.jpg" class="hide" alt="wolf">
<img id="pic2" src="http://i.imgur.com/TOUfCfL.jpg" class="hide" alt="cat">
We'll use the rendered contents of one of the two hidden images to change the image background in #img1 based on the ID Selector via CSS:
#img1 {
width: 480px;
height: 320px;
background: -moz-element(#pic1) no-repeat;
background-size: 100% 100%;
}
.hide {display: none}
Notes: It's experimental and only works with the -moz prefix in Firefox and only over background or background-image properties, also needs sizes specified.
element() Live Demo
Conclusions
Any semantic content or structural information goes in HTML.
Styling and presentational information goes in CSS.
For SEO purposes, don't hide meaningful images in CSS.
Background graphics are usually disabled when printing.
Custom tags could be used and styled from CSS, but primitive versions of Internet Explorer do not understand](IE not styling HTML5 tags (with shiv)) without Javascript or CSS guidance.
SPA's (Single Page Applications), by design, usually incorporate images in the background
Having said that, let's explore HTML tags fit for image display:
The <li> element [HTML4.01+]
Perfect usecase of the list-style-image with display: list-item method.
The <li> element, can be empty, allows flow content and it's even permitted to omit the </li> end tag.
.bulletPics > li {display: list-item}
#img1 {list-style: square inside url("http://upload.wikimedia.org/wikipedia/commons/4/4d/Nuvola_erotic.png")}
#img2 {list-style: square inside url("http://upload.wikimedia.org/wikipedia/commons/7/74/Globe_icon_2014-06-26_22-09.png")}
#img3 {list-style: square inside url("http://upload.wikimedia.org/wikipedia/commons/c/c4/Kiwi_fruit.jpg")}
<ul class="bulletPics">
<li id="img1">movie</li>
<li id="img2">earth</li>
<li id="img3">kiwi</li>
</ul>
Limitations: hard to style (width: or float: might help)
The <figure> element [HTML5+]
The figure element represents some flow content, optionally with a caption, that is self-contained (like a complete sentence) and is typically referenced as a single unit from the main flow of the document.
The element is valid with no content, but is recommended to contain a <figcaption>.
The element can thus be used to annotate illustrations, diagrams, photos, code listings, etc.
Default rendering: the element is right aligned, with both left and right padding!
FIGURE Live Demo
The <object> element [HTML4+]
To include images, authors may use the OBJECT element or the IMG element.
The data attribute is required and can have a valid MIME type as a value!
<object data="data:x-image/x,"></object>
Note: a trick to make use of the <object> tag from CSS would be to set a custom valid MimeType x-image/x followed by no data (value has no data after the required comma ,)
Default rendering: 300 x 150px, but size can be specified either in HTML or CSS.
OBJECT Live Demo
The <SVG> tag
Needs a SVG capable browser and has a <image> element for raster images
SVG Live Demo
The <canvas> element [HTML5+].
The width attribute defaults to 300, and the height attribute defaults to 150.
CANVAS Live Demo
The <input> element with type="image"
Limitations:
... the element is expected to appear button-like to indicate that the element is a button.
which Chrome follows and renders a 4x4px empty square when no text
Partial solution, set value=" ":
<input type="image" id="img1" value=" ">
INPUT type=image Live Demo
Also watch out for the upcoming <picture> element in HTML5.1, currently a working draft.
i used the empty div solution, with this CSS:
#throbber {
background-image: url(/Content/pictures/ajax-loader.gif);
background-repeat: no-repeat;
width: 48px;
height: 48px;
min-width: 48px;
min-height: 48px;
}
HTML:
<div id="throbber"></div>
I found a better way than the proposed solutions, but it does use the background-image indeed.
Compliant method (cannot confirm for IE6)
Credits: http://www.kryogenix.org/code/browser/lir/
<img src="pathTo/myImage.jpg"/>
The CSS:
img[src*="pathTo/myImage.jpg"] {
background-image: url("mynewimg.jpg"); /* lets say 20x20 */
width: 20px;
display:inline-block;
padding: 20px 0 0 0;
height: 0px !important;
/* for IE 5.5's bad box model */
height /**/:20px;
}
The old image is not seen and the new is seen as expected.
The following neat solution only works for webkit
img[src*="pathTo/myImage.jpg"] {
/* note :) */
content:'';
display:inline-block;
width: 20px;
height: 20px;
background-image: url("mynewimg.jpg"); /* lets say 20x20 */
}
They are right. IMG is a content element and CSS is about design.
But, how about when you use some content elements or properties for design purposes?
I have IMG across my web pages that must change if i change the style (the CSS).
Well this is a solution for defining IMG presentation (no really the image) in CSS style.
create a 1x1 transparent gif or png.
Assign propery "src" of IMG to that image.
Define final presentation with "background-image" in the CSS style.
It works like a charm :)
Here is a very good solution -> http://css-tricks.com/replace-the-image-in-an-img-with-css/
Pro(s) and Con(s):
(+) works with vector image that have relative width/height (a thing that RobAu's answer does not handle)
(+) is cross browser (works also for IE8+)
(+) it only uses CSS. So no need to modify the img src (or if you do not have access/do not want to change the already existing img src attribute).
(-) sorry, it does use the background css attribute :)
No you can't set the image src attribute via CSS. The closest you can get is, as you say, background or background-image. I wouldn't recommend doing that anyway as it would be somewhat illogical.
However, there is a CSS3 solution available to you, if the browsers you're targeting are able to use it. Use content:url as described in Pacerier's answer. You can find other, cross-browser solutions in the other answers below.
You can define 2 images in your HTML code and use display: none; to decide which one will be visible.
Put several images in a "controlling" container, and change the container's class instead. In CSS, add rules to manage images' visibility depending on the container's class. This will produce the same effect as changing img src property of a a single image.
HTML:
<span id="light" class="red">
<img class="red" src="red.png" />
<img class="yellow" src="yellow.png" />
<img class="green" src="green.png" />
</span>
CSS:
#light { ... }
#light * { display: none; } // all images are hidden
#light.red .red { display: inline; } // show red image when #light is red
#light.yellow .yellow { display: inline; } // .. or yellow
#light.green .green { display: inline; } // .. or green
Note that it will preload all images, like with CSS backround-images, but unlike changing img src via JS.
Some data I would leave in HTML, but it is better to define the src in CSS:
<img alt="Test Alt text" title="Title text" class="logo">
.logo {
content:url('../images/logo.png');
}
Or you could do this which I found on the interweb thingy.
https://robau.wordpress.com/2012/04/20/override-image-src-in-css/
<img src="linkToImage.jpg" class="egg">
.egg {
width: 100%;
height: 0;
padding: 0 0 200px 0;
background-image: url(linkToImage.jpg);
background-size: cover;
}
So effectively hiding the image and padding down the background. Oh what a hack but if you want an IMG tag with alt text and a background that can scale without using JavaScript?
In a project I'm working on now I created a hero block twig template
<div class="hero">
<img class="image" src="{{ bgImageSrc }}"
alt="{{ altText }}" style="background-image: url({{ bgImageSrc }});">
</div>
Alternative way
.myClass {
background: url('/img/loading_big.gif');
}
<div class="myClass"></div>
As far as I am aware of, YOU CANNOT. CSS is about style and image's src is content.
To reiterate a prior solution and to stress the pure CSS implementation here is my answer.
A Pure CSS solution is needed in cases where you are sourcing content from another site, and thus you have no control over the HTML that is delivered. In my case I am trying to remove branding of licensed source content so that the licencee does not have to advertise for the company they are buying the content from. Therefore, I'm removing their logo while keeping everything else. I should note that this is within my client's contract to do so.
{ /* image size is 204x30 */
width:0;
height:0;
padding-left:102px;
padding-right:102px;
padding-top:15px;
padding-bottom:15px;
background-image:url(http://sthstest/Style%20Library/StThomas/images/rhn_nav_logo2.gif);
}
I know this is a really old question however no answers provide the proper reasoning for why this can never be done. While you can "do" what you are looking for you cannot do it in a valid way. In order to have a valid img tag it must have the src and alt attributes.
So any of the answers giving a way to do this with an img tag that does not use the src attribute are promoting use of invalid code.
In short: what you are looking for cannot be done legally within the structure of the syntax.
Source: W3 Validator
If you don't want to set a background property then you can't set the src attribute of an image using only CSS.
Alternatively you can use JavaScript to do such a thing.
Using CSS, it can't be done. But, if you are using JQuery, something like this will do the trick:
$("img.myClass").attr("src", "http://somwhere");
You can convert it with JS:
$('.image-class').each(function(){
var processing = $(this).attr('src');
$(this).parent().css({'background-image':'url('+processing+')'});
$(this).hide();
});
If you are trying to add an image in a button dynamically based on the context of your project, you can use the ? take to reference the source based on an outcome. Here I am using mvvm design to let my Model.Phases[0] value determine whether I want my button to be populated with images of a lightbulb on or off based on the value of the light phase.
Not sure if this helps. I'm using JqueryUI, Blueprint, and CSS. The class definition should allow you to style the button based on whatever you'd like.
<button>
<img class="#(Model.Phases[0] ? "light-on": "light-off")" src="#(Model.Phases[0] ? "~/Images/LightBulbOn.png" : "~/Images/LightBulbOff.png")"/>
<img class="#(Model.Phases[0] ? "light-on": "light-off")" src="#(Model.Phases[0] ? "~/Images/LightBulbOn.png" : "~/Images/LightBulbOff.png")"/>
<img class="#(Model.Phases[0] ? "light-on": "light-off")" src="#(Model.Phases[0] ? "~/Images/LightBulbOn.png" : "~/Images/LightBulbOff.png")"/>
I would add this: background image could be also positioned with background-position: x y; (x horizontal y vertical). (..)
My case, CSS:
(..)
#header {
height: 100px;
background-image: url(http://.../head6.jpg);
background-position: center;
background-repeat: no-repeat;
background-color: grey;
(..)
}
(...)
HTMl Code:
<!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="css destination" />
</head>
<body>
<!-- click-able pic with link -->
<a href="site you want">
<!-- Take the off if you don't want click-able link -->
<h1 id(or class)="nameOfClassorid">
<span>Text that is not important</span>
</h1>
</a>
</body>
</html>
Css Code:
span {
display: none;
}
h1 id or class {
height: of pic;
width: of pic;
/* Only flaw (so far) read bottom */
background-image:url(/* "image destination" */);
}
h1 id or class:hover {
/* Now the awesome part */
background-image:url(/* 'new background!!!' */);
}
I've been studying html after school for a few days, and wanted to know how to do this. Found out the background and then put 2 and 2 together.
This works 100% I checked, if not make sure you fill in necessary things!!!
We need to specify height, because without it there would be nothing!!!
I'll leave this basic shell you can add-on.
Example:
<!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="style.css" />
</head>
<body>
<a href="http:localhost">
<h1>
<span>Text that is not important</span>
</h1>
</a>
</body>
</html>
span {
display: none;
}
h1 {
height: 100px;
width: 100px;
background-image:url("http://linuxlog.org/wp-content/uploads/2011/01/Ubuntu-Desktop-#-2011-01-11-191526-300x225.png");
}
h1:hover {
height: 300px;
width: 300px;
background-image:url("http://cdn.css-tricks.com/images/ads/wufoo-600x600-red.png");
}
P.S. Yes I am a Linux user ;)
Any method based on background or background-image is likely to fail when user prints the document with "print background colors and images" disabled.
Which is unfortunately typical browser's default.
The only print-friendly and cross-browser compatible method here is the one proposed by Bronx.
Just use HTML5 :)
<picture>
<source srcset="smaller.jpg" media="(max-width: 768px)">
<source srcset="default.jpg">
<img srcset="default.jpg" alt="My default image">
</picture>