Is it possible to set the src
attribute value in CSS? At present, what I am doing is:
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");
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:
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!
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');
}
<style>
body {
--imgid: 1025; /* optional default img */
}
.shoes {
--imgid: 21;
}
.bridge {
--imgid: 84;
}
img {
--src: "//i.picsum.photos/id/"var(--imgid)"/180/180.jpg"
}
</style>
<script>
function loadIMG(img) {
img.src = getComputedStyle(img) // compute style for img
.getPropertyValue("--src") // get css property
.replace(/[" ]/g, ""); // strip quotes and space
}
</script>
<img src onerror=loadIMG(this) class=bridge>
<img src onerror=loadIMG(this) class=shoes>
<img src onerror=loadIMG(this)>
src
definition on an <IMG> triggers the onerror handler: loadIMG functionI 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 */
}
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-image
s, but unlike changing img src
via JS.