How to Set the Equivalent of "src" Attribute of an <img> Tag in CSS

Commonly when we need to specify the URL of an image, we use the src attribute. But, if you need to specify the URL differently, you can use the content property with the needed URL as a value.

So, in this snippet, we’re going to demonstrate the possible solutions of setting the equivalent of a src attribute of an <img> tag in CSS.

Let’s start with creating HTML.

Create HTML

  • Use an <img> with a class name “image”.
<img class="image" alt="Image"/>

Add CSS

  • Add the content property with the URL as a value.
.image {
  content: url('https://www.w3docs.com/uploads/media/default/0001/01/477719675fecaac0362957c214fb9aa56fca99b5.jpeg');
}

Here you can see the full code.

Example of using the content property as an equivalent to the src attribute:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      .image {
        content: url('https://www.w3docs.com/uploads/media/default/0001/01/477719675fecaac0362957c214fb9aa56fca99b5.jpeg');
      }
    </style>
  </head>
  <body>
    <img class="image" alt="Image" />
  </body>
</html>
However, the problem of setting an equivalent to the src attribute does not have a cross-browser solution.

In the example above, the image will appear in browsers that support content: url. Note that even in browsers supporting assigning the content to <img>, the image may change its behavior (it may ignore size attributes). In Chrome and Safari, it loses some options of the context menu.

Example of using the background-image property as an equivalent to the src attribute:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      img:not([src]) {
        background-image: url('https://www.w3docs.com/uploads/media/default/0001/01/477719675fecaac0362957c214fb9aa56fca99b5.jpeg');
        background-repeat: no-repeat;
        background-size: auto;
        display: inline-block;
        height: 250px;
        width: 250px;
      }
    </style>
  </head>
  <body>
    <img class="image123" alt="Image" />
  </body>
</html>

Here, we added a fallback in case no src is set. The height and width of the image must be known. Also, we added the display property set to “inline-block”.