Reputation: 1113
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?
Upvotes: 7
Views: 45165
Reputation: 81
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);
}
}
Upvotes: 8
Reputation: 5743
If you don't want to use backgrounds nor use javascript, you layer 2 images with different src on top of each other (using absolute positioning) and use CSS to hide one or another. Visually it will be the same then changing the src.
Upvotes: 0
Reputation: 3694
I found this article that might be useful. It actually changes background of an image
here is the example in case website goes missing:
HTML
<html>
<body>
<div class="header">
<img class="banner" src="http://notrealdomain1.com/banner.png">
</div>
</body>
</html>
CSS
/* All in one selector */
.banner {
display: block;
-moz-box-sizing: border-box;
box-sizing: border-box;
background: url(http://notrealdomain2.com/newbanner.png) no-repeat;
width: 180px; /* Width of new image */
height: 236px; /* Height of new image */
padding-left: 180px; /* Equal to width of new image */
}
Upvotes: 0
Reputation: 4055
You cannot really do that, however, if you do need to do that using CSS, you can do it for two images with the same size like this:
<style>
img {
width:0;
height:0;
display:block;
background: url('2.png') no-repeat bottom left;
padding-left:196px;
padding-bottom:187px;
}
</style>
<img src="1.png">
Only tested it in FF3.6 though.
Upvotes: 0
Reputation: 449633
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.
Upvotes: 8
Reputation: 142977
That is not possible with CSS. However, this is very easy with Javascript:
document.getElementById("IdOfImage").src = "SourceOfImage";
Upvotes: 4