Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

css - how to change image source by its id?

Tags:

html

css

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?

like image 426
gabi Avatar asked Feb 27 '11 17:02

gabi


3 Answers

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

  • The ability to set an alt text
  • Resizing
  • Printing (most browsers don't print background images)
  • Search engine indexing (probably)

the 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.

like image 183
Pekka Avatar answered Oct 13 '22 00:10

Pekka


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);
    }
}
like image 26
Charbrec Avatar answered Oct 13 '22 01:10

Charbrec


That is not possible with CSS. However, this is very easy with Javascript:

 document.getElementById("IdOfImage").src = "SourceOfImage";
like image 30
Peter Olson Avatar answered Oct 13 '22 00:10

Peter Olson