Appearance
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. However, CSS does not provide a direct equivalent for the src attribute on regular elements. The content property only applies to ::before and ::after pseudo-elements, not to <img> tags directly. If you need to specify an image URL via CSS, you can use the background-image property or apply content to a pseudo-element.
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”.
HTML Example:
html
<img class="image" alt="Image"/>Add CSS
- Apply the
contentproperty to a::beforepseudo-element with the URL as a value.
CSS Example:
css
.image::before {
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:
Example of using the content property as an equivalent to the src attribute:
html
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
.image::before {
content: url('https://www.w3docs.com/uploads/media/default/0001/01/477719675fecaac0362957c214fb9aa56fca99b5.jpeg');
}
</style>
</head>
<body>
<img class="image" alt="Image" />
</body>
</html>WARNING
Note that these CSS approaches are fragile workarounds rather than robust replacements for the src attribute. The content property only works on pseudo-elements, so it won't replace the actual image node. Using background-image on an <img> element is non-standard; the image may ignore size attributes, lose context menu options in some browsers, and may not trigger image-specific behaviors like loading states or accessibility announcements.
Example of using the background-image property as an equivalent to the src attribute:
Example of using the background-image property as an equivalent to the src attribute:
html
<!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”.