Set src using just CSS

Sometimes we need to change the src of an <img> element, but we don’t have access to the HTML, like when styling a plugin.

But, CSS is our friend here, and we can use the url pseudo element to set the <img> src.

<style>
.my-class {
content:url("http://imgur.com/SZ8Cm.jpg");
}
</style>
<img class="my-class">

Check out this JSFiddle. Should work in IE9 and all new browsers.

Leave a Comment

Your email address will not be published. Required fields are marked *