简体   繁体   中英

How do I change an image source with CSS?

I would like to change the displayed image just with CSS

<a href="/"><img id="image1" src="http://somepic.jpg"></a>

since there is no css for src I think, I must make it transparent and display another image in the background somehow?

You can't. You could change it with Javascript.

With CSS, you could set the image to display:none; set a background-image on a parent element.

I would suggest the following alternatives:

  • (especially) If the <img> s lend no semantic value, remove them entirely in favor of putting background-image s on other elements.
  • If the new images lend semantic value to the document, and you're ok with them being pre-loaded, insert them as additional <img> s and just hide one or the other with css (assuming this is for a hover or other similarly conditional effect)
  • Change the src with javaScript

Although its true that CSS is made for presentation only but CAS (Cascading Attribute Sheet) is been proposed and under thought, also I think for basic purpose below code should work for you ,

<style>
a:after
{
content:url(your_image.jpg);
}
#image1
{
display:none;
}
</style>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM