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;
}
Author by
bristol.james
Updated on August 05, 2022Comments
-
bristol.james over 1 year
I need to define an <img>'s src attribute in CSS. Is there a way to specify this attribute?
-
Rob Audenaerde over 11 years
-
aldebaran about 10 years
-
-
Quentin about 14 yearsIndeed.
<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 almost 11 yearsIt doesn't work if you need that
<img>
to print, which was the situation I'm in. -
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 over 9 years@GregoryLewis I think this is better: stackoverflow.com/questions/2182716/…
-
Rafiki about 9 yearsI 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 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 over 6 yearsToday, 2017 year,
background-image
is not the solution. Making this, I have 2 images -
Kiquenet about 6 yearshave you 1x1 transparent gif or png for download it ? any full sample with
html and css code
? -
Kiquenet about 6 yearsimg hover too ?
-
Sebastian Kropp over 5 yearsCurrently, Data URIs only work in Chrome.
content: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='181' .....
-
Bruno Polo almost 3 yearshow is this not the accepted answer? today i think this is widely implemented in browsers
-
fragant about 2 yearsNot for Firefox 91.5 though