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.
1. Using content: url
A quick, not very cross-compatible solution is to drop the src attribute and use content:url() in CSS.
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.
How to Set img src using CSS
Sometimes, you want to change the src attribute of an img without using HTML.
For example, going from this:
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:
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 :
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!
If you want to learn about web development, founding a start-up, bootstrapping a SaaS, and more, follow me on Twitter! You can also join the conversation over at our official Discord!
Give feedback on this page , tweet at us, or join our Discord !
Img tag src in css
Тег предназначен для отображения на веб-странице изображений в графическом формате GIF, JPEG или PNG. Адрес файла с картинкой задаётся через атрибут src . Если необходимо, то рисунок можно сделать ссылкой на другой файл, поместив тег
в контейнер . При этом вокруг изображения отображается рамка, которую можно убрать, добавив атрибут border=»0″ в тег
.
Рисунки также могут применяться в качестве карт-изображений, когда картинка содержит активные области, выступающие в качестве ссылок. Такая карта по внешнему виду ничем не отличается от обычного изображения, но при этом оно может быть разбито на невидимые зоны разной формы, где каждая из областей служит ссылкой.
Синтаксис
Атрибуты
align Определяет как рисунок будет выравниваться по краю и способ обтекания текстом. alt Альтернативный текст для изображения. border Толщина рамки вокруг изображения. height Высота изображения. hspace Горизонтальный отступ от изображения до окружающего контента. ismap Говорит браузеру, что картинка является серверной картой-изображением. longdesc Указывает адрес документа, где содержится аннотация к картинке. lowsrc Адрес изображения низкого качества. src Путь к графическому файлу. vspace Вертикальный отступ от изображения до окружающего контента. width Ширина изображения. usemap Ссылка на тег , содержащий координаты для клиентской карты-изображения.
Также для этого тега доступны универсальные атрибуты и события.
Закрывающий тег
Lorem ipsum dolor sit amet.