Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

html

css

image

src

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.

like image 572
Rakesh Juyal Avatar asked Feb 02 '10 08:02

Rakesh Juyal


People also ask

Is src an attribute of IMG tag?

The <img> tag has two required attributes: src - Specifies the path to the image. alt - Specifies an alternate text for the image, if the image for some reason cannot be displayed.

Can you use src in CSS?

You can simulate having a src attribute by using the content attribute in CSS, and passing in the image path url() .

Can you change img src?

The required src attribute specifies the URL of an image. Note: The src property can be changed at any time. However, the new image inherits the height and width attributes of the original image, if not new height and width properties are specified.

Can we use img tag in CSS?

IMG is a content element and CSS is about design. But, how about when you use some content elements or properties for design purposes? I have IMG across my web pages that must change if i change the style (the CSS). Well this is a solution for defining IMG presentation (no really the image) in CSS style.


1 Answers

Use content:url("image.jpg").

Full working solution (Live Demo):

<!doctype html>    <style>  .MyClass123{  	content:url("http://imgur.com/SZ8Cm.jpg");  }  </style>    <img class="MyClass123"/>

Tested and working:

  • Chrome 14.0.835.163
  • Safari 4.0.5
  • Opera 10.6

Tested and Not working:

  • FireFox 40.0.2 (observing Developer Network Tools, you can see that the URL loads, but the image is not displayed)
  • Internet Explorer 11.0.9600.17905 (URL never loads)
like image 152
Pacerier Avatar answered Oct 16 '22 01:10

Pacerier