How to Set img src using CSS
Table of Contents
Sometimes, you want to change the src
attribute of an img
without using HTML.
For example, going from this:
HTML<img />
To this:
HTML<img src="/path/here/to/image.png" />
A solution
You can simulate having a src
attribute by using the content
attribute in CSS, and passing in the image path url()
.
For example, if you want to simulate changing the src
attribute of an img
to /path/here/to/image.png
, you can do this:
CSSimg {
content: url("/path/here/to/image.png");
}
This can work in some cases, but it's not recommended, especially because there is a better solution.
A better solution
A better way to add a src
attribute to an img
is to use CSS targeting to add a background-image
. The caveat here is that you need to know and provide the image's dimensions.
Here's how to target the img
and add a background-image
, with an image of dimensions 20rem
by 10rem
:
CSSimg[src*="/path/here/to/image.png"] {
background-image: url("/path/here/to/image.png");
width: 20rem;
height: 10rem;
padding: 10rem 0 0 0;
}
Once you do that, you should see the image in the browser, all without changing the src
attribute.
Conclusion
If you don't want to change the src
attribute of an img
to a different image using HTML, you have two solutions to get the image to display in the browser using CSS.
Hopefully, this post has given you a solution that works for your needs. Happy coding!
- Managing PHP Dependencies with Composer
- Getting Started with Express
- How to Serve Static Files with Nginx and Docker
- How to deploy an Express app using Docker
- How to deploy a Node app using Docker
- Learn how to use v-model with a custom Vue component
- Using Puppeteer and Jest for End-to-End Testing
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Getting User Location using JavaScript's Geolocation API
- Learn how to build a Slack Bot using Node.js
- Using Push.js to Display Web Browser Notifications
- Getting Started with React