How to Set img src using CSS

Published Apr 7, 2021  ∙  Updated May 2, 2022

I needed a way to set the src attribute of my img tags using CSS.

I didn’t want to define the path in HTML.

<img src="/path/to/image.png" />

Quick Solution

A quick, not very cross-compatible solution is to drop the src attribute and use content:url() in CSS.

<img />
img {
  content: url("/path/to/image.png");

This is known to have issues in FireFox and IE, but it is much cleaner than this next solution.

More Elaborate Solution

Instead of dropping the src tag, we can use it to target that img element in our styles.

Let’s say our newimage.png has width x height dimensions of 200px x 100px.

img[src*="/path/to/image.png"] {
  background-image: url("/path/to/newimage.png");
  width: 200px;
  height: 0px !important;
  height /**/: 100px;
  padding: 100px 0 0 0;

We need to manually specify width and height.

Additionally, we accomodate for IE versions that mishandle the box model (height /**/). Some code formatters will remove the space between height and /**/, which is needed, so ensure that the space is there after reformatting.