Is it possible to set the equivalent of a src attribute of an img tag in CSS?

Viewed 703981

Is it possible to set the src attribute value in CSS? At present, what I am doing is:

<img src="pathTo/myImage.jpg"/>

and I want it to be something like this

<img class="myClass"/>
.myClass {
    some-src-property: url("pathTo/myImage.jpg");

I want to do this without using the background or background-image: properties in CSS.

24 Answers

No you can't set the image src attribute via CSS. The closest you can get is, as you say, background or background-image. I wouldn't recommend doing that anyway as it would be somewhat illogical.

However, there is a CSS3 solution available to you, if the browsers you're targeting are able to use it. Use content:url as described in Pacerier's answer. You can find other, cross-browser solutions in the other answers below.

Some data I would leave in HTML, but it is better to define the src in CSS:

<img alt="Test Alt text" title="Title text" class="logo">

.logo {
    content:url('../images/logo.png');
}

As far as I am aware of, YOU CANNOT. CSS is about style and image's src is content.

If you don't want to set a background property then you can't set the src attribute of an image using only CSS.

Alternatively you can use JavaScript to do such a thing.

Using CSS, it can't be done. But, if you are using JQuery, something like this will do the trick:

$("img.myClass").attr("src", "http://somwhere");
Related