How to Set img src using CSS
I needed a way to set the src attribute of my img tags using CSS.
I didn’t want to define the path in HTML.
<img src="/path/to/image.png" />
1. Using content: url
A quick, not very cross-compatible solution is to drop the src attribute and use content:url() in CSS.
<img />
img {
content: url("/path/to/image.png");
}
This is known to have issues in FireFox and IE, but it is much cleaner than this next solution.
2. Using background-image and padding
Instead of dropping the src tag, we can use it to target that img element in our styles (we can also target the img using a class or id).
Let’s say our newimage.png has width x height dimensions of 200px x 100px.
We can set the background-image to be the new image and push the inline image out of the way using padding.
img[src*="/path/to/image.png"] {
background: url("/path/to/newimage.png") no-repeat;
width: 200px; /* Width of new image */
height: 0px !important;
height /**/: 100px; /* Height of new image */
padding: 100px 0 0 0; /* Height of new image */
}
Here, we’ll need to manually specify width and height.
Additionally, we accomodate for IE versions that mishandle the box model (height /**/). Some code formatters will remove the space between height and /**/, which is needed, so ensure that the space is there after reformatting.
It may also be helpful to include
box-sizing: border-box;in order to force padding and borders into the total width.