Is it possible to set the equivalent of a src attribute of an img tag in CSS?
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!
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)