← Blog

Set <img> src using just CSS

WordPress1 min read

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.

Stuck on something like this?

I help businesses and agencies with WordPress, WooCommerce and JavaScript problems, from one-off fixes to ongoing support.