Define an <img>'s src attribute in CSS

458,909

Solution 1

#divID {
    background-image: url("http://imageurlhere.com");
    background-repeat: no-repeat;
    width: auto; /*or your image's width*/
    height: auto; /*or your image's height*/
    margin: 0;
    padding: 0;
}

Solution 2

just this as img tag is a content element

img {
    content:url(http://example.com/image.png);
}

Solution 3

No there isn't. You can specify a background image but that's not the same thing.

Solution 4

CSS is not used to define values to DOM element attributes, javascript would be more suitable for this.

Solution 5

No. The closest you can get is setting a background image:

<div id="myimage"></div>

#myimage {
  width: 20px;
  height: 20px;
  background: white url(myimage.gif) no-repeat;
}
Share:
458,909
bristol.james
Author by

bristol.james

Updated on August 05, 2022

Comments

  • bristol.james
    bristol.james over 1 year

    I need to define an <img>'s src attribute in CSS. Is there a way to specify this attribute?

  • Quentin
    Quentin about 14 years
    Indeed. <img> represents a content image. If the image isn't content then it shouldn't be an <img> element. If it is content, then it should be. If the content is duplicated on multiple pages (such as being part of a menu) then the HTML for it should be too (e.g. using a template system) just like any other duplicated content.
  • Katie Kilian
    Katie Kilian almost 11 years
    It doesn't work if you need that <img> to print, which was the situation I'm in.
  • TARKUS
    TARKUS over 10 years
    @zipcodeman : That's too bad. There are some limitations to the background-image: method. Like, you have no control over the dimensions of the image. You can make the image space bigger, of course, just not the actual image.
  • mila
    mila over 9 years
    @GregoryLewis I think this is better: stackoverflow.com/questions/2182716/…
  • Rafiki
    Rafiki about 9 years
    I was about to post the same article, it works perfectly for me, and I have to support IE on my site. if it works for IE...
  • Lee
    Lee over 8 years
    @zipcodeman - You can change the size of the image this way by using background-size:cover, and then changing the height and width.
  • Marcelo
    Marcelo over 6 years
    Today, 2017 year, background-image is not the solution. Making this, I have 2 images
  • Kiquenet
    Kiquenet about 6 years
    have you 1x1 transparent gif or png for download it ? any full sample with html and css code ?
  • Kiquenet
    Kiquenet about 6 years
    img hover too ?
  • Sebastian Kropp
    Sebastian Kropp over 5 years
    Currently, Data URIs only work in Chrome. content: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='181' .....
  • Bruno Polo
    Bruno Polo almost 3 years
    how is this not the accepted answer? today i think this is widely implemented in browsers
  • fragant
    fragant about 2 years
    Not for Firefox 91.5 though