Does anyone know how can I control the image source from the CSS?
I need to be able to change the image src from the CSS. I have loop printing < img id=.. >
tags, and for every id it different image. I want to be able to set the source by its id from the style css area.
Does anyone know how to do this?
This is not possible: The image's source is part of the markup, not CSS.
The only workaround would be having div
elements with background-image
properties instead. Those you could set from within the style sheet:
<div id="image1"></div>
#image1 { width: 100px; height: 50px; background-image: url(image.gif); }
However, with this method you lose all the img
tag's advantages like
alt
textthe only other alternative is by using JavaScript, but that obviously won't work if JavaScript is disabled, which makes it a no-no in my view.
This is now possible with CSS3 using the Content style. I use this to swap images within a slider based on window size through media queries.
Edit: When I originally posted this, I was unaware that it only worked in Webkit at the moment. But I doubt it will take long before it gains more functionality across browsers.
HTML
<img class="img1" src="image.jpg">
CSS
@media (min-width: 768px) {
.img1 {
content: url(image.jpg);
}
}
@media (max-width: 767px){
.img1 {
content: url(new-image.jpg);
}
}
That is not possible with CSS. However, this is very easy with Javascript:
document.getElementById("IdOfImage").src = "SourceOfImage";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With