Define an <img>'s src attribute in CSS
CssAttributesImageCss Problem Overview
I need to define an <img>'s src attribute in CSS. Is there a way to specify this attribute?
Css Solutions
Solution 1 - Css
just this as img tag is a content element
img {
content:url(http://example.com/image.png);
}
Solution 2 - Css
#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 3 - Css
No there isn't. You can specify a background image but that's not the same thing.
Solution 4 - Css
CSS is not used to define values to DOM element attributes, javascript would be more suitable for this.
Solution 5 - Css
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;
}
Solution 6 - Css
After trying these solutions I still wasn't satisfied but I found a solution in this article and it works in Chrome, Firefox, Opera, Safari, IE8+
#divId {
display: block;
-moz-box-sizing: border-box;
box-sizing: border-box;
background: url(http://notrealdomain2.com/newbanner.png) no-repeat;
width: 180px; /* Width of new image */
height: 236px; /* Height of new image */
padding-left: 180px; /* Equal to width of new image */
}
Solution 7 - Css
They are right. 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: create a 1x1 transparent gif or png.
2: Assign propery "src" of IMG to that image.
3: Define final presentation with "background-image" in the CSS style.
It works like a charm :)