HTML Images
Images can improve the design and the appearance of a web page.
Example
Example
Example
HTML Images Syntax
The HTML <img> tag is used to embed an image in a web page.
Images are not technically inserted into a web page; images are linked to web pages. The <img> tag creates a holding space for the referenced image.
The <img> tag is empty, it contains attributes only, and does not have a closing tag.
The <img> tag has two required attributes:
- src — Specifies the path to the image
- alt — Specifies an alternate text for the image
Syntax
The src Attribute
The required src attribute specifies the path (URL) to the image.
Note: When a web page loads, it is the browser, at that moment, that gets the image from a web server and inserts it into the page. Therefore, make sure that the image actually stays in the same spot in relation to the web page, otherwise your visitors will get a broken link icon. The broken link icon and the alt text are shown if the browser cannot find the image.
Example
The alt Attribute
The required alt attribute provides an alternate text for an image, if the user for some reason cannot view it (because of slow connection, an error in the src attribute, or if the user uses a screen reader).
The value of the alt attribute should describe the image:
Example
If a browser cannot find an image, it will display the value of the alt attribute:
Example
Tip: A screen reader is a software program that reads the HTML code, and allows the user to "listen" to the content. Screen readers are useful for people who are visually impaired or learning disabled.
Image Size — Width and Height
You can use the style attribute to specify the width and height of an image.
Example
Alternatively, you can use the width and height attributes:
Example
The width and height attributes always define the width and height of the image in pixels.
Note: Always specify the width and height of an image. If width and height are not specified, the web page might flicker while the image loads.
Width and Height, or Style?
The width , height , and style attributes are all valid in HTML.
However, we suggest using the style attribute. It prevents styles sheets from changing the size of images:
Example
<img src="html5.gif" alt="HTML5 Icon" style="width:128px;height:128px;">
Images in Another Folder
If you have your images in a sub-folder, you must include the folder name in the src attribute:
Example
Images on Another Server/Website
Some web sites point to an image on another server.
To point to an image on another server, you must specify an absolute (full) URL in the src attribute:
Example
Notes on external images: External images might be under copyright. If you do not get permission to use it, you may be in violation of copyright laws. In addition, you cannot control external images; they can suddenly be removed or changed.
Animated Images
HTML allows animated GIFs:
Example
Image as a Link
To use an image as a link, put the <img> tag inside the <a> tag:
Example
Image Floating
Use the CSS float property to let the image float to the right or to the left of a text:
Example
<p><img src="smiley.gif" alt="Smiley face" style="float:right;width:42px;height:42px;">
The image will float to the right of the text.</p>
<p><img src="smiley.gif" alt="Smiley face" style="float:left;width:42px;height:42px;">
The image will float to the left of the text.</p>
Tip: To learn more about CSS Float, read our CSS Float Tutorial.
Common Image Formats
Here are the most common image file types, which are supported in all browsers (Chrome, Edge, Firefox, Safari, Opera):
| Abbreviation | File Format | File Extension |
|---|---|---|
| APNG | Animated Portable Network Graphics | .apng |
| GIF | Graphics Interchange Format | .gif |
| ICO | Microsoft Icon | .ico, .cur |
| JPEG | Joint Photographic Expert Group image | .jpg, .jpeg, .jfif, .pjpeg, .pjp |
| PNG | Portable Network Graphics | .png |
| SVG | Scalable Vector Graphics | .svg |
Chapter Summary
- Use the HTML <img> element to define an image
- Use the HTML src attribute to define the URL of the image
- Use the HTML alt attribute to define an alternate text for an image, if it cannot be displayed
- Use the HTML width and height attributes or the CSS width and height properties to define the size of the image
- Use the CSS float property to let the image float to the left or to the right
Note: Loading large images takes time, and can slow down your web page. Use images carefully.
HTML Exercises
HTML Image Tags
| Tag | Description |
|---|---|
| <img> | Defines an image |
| <map> | Defines an image map |
| <area> | Defines a clickable area inside an image map |
| <picture> | Defines a container for multiple image resources |
For a complete list of all available HTML tags, visit our HTML Tag Reference.
HTML picture tag in practice — PNG and WEBP formats
![]()
It is a known problem how to include an image in different sizes — fortunately, almost all browser supports <picture> tag. It works especially well with modern image formats, like webp, which gives us nice and easy solution to reduce page size and improve user experience.
Important note
I have created a GH page for repository for this post:
HTML picture tag in practice
GH-page
So you can try it live. For example, open DevTools and switch between mobile, tablet, or orientations and see in Network tab when it loads proper image.
Prerequisites
HTML picture tag
<picture> tag allows us to load different images for different requirements. It may contain zero or more <source> elements and one <img> tag as a fallback for older browsers.
Support is quite wide today:
Can I use. Support tables for HTML5, CSS3, etc
"Can I use" provides up-to-date browser support tables for support of front-end web technologies on desktop and mobile…
If you have to support old browser like IE 11 or Safari on iOS 9.2.x, you can use picture polyfill:
Picturefill
The picture element, srcset and sizes attributes, and associated features allow web developers to deliver an…
Google’s WEBP image format
WEBP format was introduced by Google, they provide some interesting case studies which provide results proving how effective it is:
WebP Compression Study | WebP | Google Developers
We describe two types of evaluations. In the first case, we study the additional compression achieved by WebP at the…
Lossless and Transparency Encoding in WebP | WebP | Google Developers
WebP supports lossless and translucent images, making it an alternative to the PNG format. Many of the fundamental…
But what about browsers support? As we can find on CanIUse, it is supported only on Chromium-based browsers:
Can I use. Support tables for HTML5, CSS3, etc
"Can I use" provides up-to-date browser support tables for support of front-end web technologies on desktop and mobile…
Is it a problem? I don’t think so. Webp support is being discussed on Mozilla forums, so it’s a possibility that sooner or later it will be supported:
1294490 — (WebP) Implement experimental WebP image support
ASSIGNED (aosmond) in Core — ImageLib. Last updated 2018-08-29.
Also, WEBP is under consideration in Microsoft Edge browser:
WebP image format support
WebP is an image format that provides lossless and lossy compression for images on the web…
You can “speed up” WEBP support in Edge by voting for this idea on this page: WebP image format support. Every vote is important for the faster Web!
Implementation
I’ve created a Github repo related to this article:
radek-anuszewski/HTML-picture-tag-in-practice
HTML Picture tag in practice. Contribute to radek-anuszewski/HTML-picture-tag-in-practice development by creating an…
Where you can find how end result looks like.
I want to divide implementation section to 5 subsections:
- Very large 4k screens, 1921px and wider
- Regular desktop/laptop screens, from 1281px to1920px width
- Tablet landscape, from 461px to 1280px width
- Tablet portrait, from 461px to 1280px width
- Mobile screens, to 460px width
And each sub-section will have 2 versions — regular PNG image and WEBP image. As an example I want to use vargazs’s photo from Pixabay:
Gratis obraz na Pixabay — Rower, Rowerzysta, Drogi
Pobierz darmowe zdjęcie o Rower Rowerzysta Drogi z obszernej biblioteki zdjęć i filmów Pixabay.
Which is available for free download with many interesting resolutions.
Implementation
Starting point
The starting point looks like this:
There is no <source> defined, so fallback with <img> tag is used.
What is the size of used image? Let’s see:
And now we can start to add images designed for particular size.
How to create WEBP image?
There is many online converters, but I want to use fastest way in my opinion, converting from Intellij IDEA:
Quite big drawback of this solution is that Intellij overrides base image, so I have to make a copy and make convertion in different folder.
Quick note:
Below the same image with different sizes is used, but it’s common to use different images for different screens, for example image for mobile has less details than for 4K screen
Very large screens
I’ve created folder named very-large and placed here image 4000×1591 size. I’ve added a source tag˛with proper PNG image type (it’s very important) and media query needed for large screens: media=”(min-width: 1921px)” .
Now code looks like this:
Because my screen is 1366px I have to fake large resolution with Chrome Developer Tools:
How it looks like in Network panel?
Proper image was loaded, but can’t we make it smaller? 2.9 MB could be way too much on slower network.
Let’s use WEBP lossless compressed version and add it to code:
2 things are very important:
- I’ve added type=”image/webp” which is used by browser to decide whether this type of image is supported or not.
- WEBP image has to be above regular version, because browser takes first source which meets criteria defined in media .
What is the size of new image?
WEBP image is 3 times smaller than original image! It makes a huge difference, especially when many images are used on the site. But what if we don’t need image with such a large size?
Regular desktop/laptop screens
From vargazs’s Pixabay site I have downloaded PNG image with 1920×763 size and named it bike-regular.png . With IDE I have created WEBP version. I’ve also added 2 new sources with media=”(min-width: 1281px) and (max-width: 1920px)” , to load proper image:
What is the size difference? Let’s compare PNG size (for test, WEBP image was removed with HTML comment) and WEBP image:
WEBP image is 200 KB smaller than PNG version. The result isn’t as significant as with previous example, but remember — lossless compresion is used, lossy compresion could provide much smaller WEBP image.
Regular desktop/laptop screens with 75% encoding quality WEBP
You have to see that:
As you can see, 75% encoded image is 10 times smaller than lossless WEBP and 15 times smaller than PNG! I’m not a UX guy so it’s hard to me to see quality decrease, for me images are the same. The best solution is to always try to experiment with encoding quality — results could be amazing. Of course, it should be confirmed by UX person that quality losses are unnoticeable.
Important note!
Because many laptops have 1366px screen, it may be a good practice to divide media=”(min-width: 1281px) and (max-width: 1920px)” breakpoint to 2 breakpoints: media=”(min-width: 1367px) and (max-width: 1920px)” and media=”(min-width: 1281px) and (max-width: 1366px)” and provide separated images with 1920px and 1366px width.By this way, every screen get more accurate image which allows to further reduce the size of the page.
Tablet landscape, tablet portrait
For the sake of simplicity, for both directions I have used the same image with 1280×509 size, but named bike-tablet-landscape for horizontal and bike-tablet-portrait for vertical view. It could be switched in Chrome Developer Tools.
Let’s see code changes:
Media queries were extended with (orientation: portrait) and (orientation: landscape) to differ between directions.
Let’s see image sizes:
Again, size descrease is noticeable but not astonishing. However, 75% WEBP encoding quality does its job well:
Mobile screens
For the last example I’ve used 640×254 image. This image is displayed with media=”(max-width: 460px)” rule.
Изображения в HTML

Данная статья написана командой Vertex Academy. Это одна из статей из нашего Самоучителя по HTML&CSS. Надеемся, что данная статья Вам будет полезна. Приятного прочтения!
Изображения моментально дают нам понять, насколько данный сайт или статья могут быть для нас интересными, создают настроение, по новому могут раскрыть тему. Иногда одно фото стоит тысячи слов.
Но и частить ими не стоит, если вы не инстаграм или интернет-магазин. Желательно, чтобы изображения:
- были информативными
- соответствовали цветовой гамме вашего сайта
- были уместны
Если у вас нет подходящего фото, можно воспользоваться так называемым фотостоком ( фотобанком ) — местом, где хранится множество фотографий, иллюстраций и векторной графики. Таких ресурсов море, вы возможно даже слышали об одном из крупнейших — Shutterstock, но скачивания там платные.
Для тех, кто не любит переплачивать, в конце статьи мы приготовили бонус — список нескольких фотобанков , где можно скачать огромное количество качественных красивых материалов совершенно бесплатно
Форматы изображений
Во Всемирной паутине в основном используются 3 вида изображений:
gif (Graphics Interchange Format — формат для обмена изображениями)
это первый формат, который начал использоваться в интернете. Плюсы такого формата — наличие анимации и маленький размер, страница загружается быстро. К тому же он поддерживает прозрачность. Недостаток — используется только 256 цветов (собственно потому и размер маленький), т.е. его нельзя использовать для полноцветных изображений.

jpeg , он же jpg (Joint Photographic Experts Group — Объединенная группа экспертов по фотографии — так называется организация-разработчик)
подходит для создания полноцветных, высококачественных изображений, фотографий . Размер таких картинок велик, поэтому они обычно дают большую нагрузку на сервер. Если нужно сжать jpeg (для меньшего веса картинки) рекомендуем брать размер итогового изображения кратный восьми , так потери качества будут минимальными.
png (Portable Network Graphics — Портативная сетевая графика. Произносится так же как ping, т.е. [ pɪŋ ])
этот формат изначально разрабатывался для веба, т.е. изображение обычно мало «весит» и не тормозит страницу при загрузке. Этот формат создан на замену устаревшего gif, но в отличие от него, не поддерживает анимацию. Png-8 , как и gif, использует всего 256 цветов. Формат png-24 поддерживает 16 млн цветов, правда и вес уже немаленький. Png-32 содержит столько же цветов, как и png-24, и плюс к этому позволяет получить изображение с прозрачным фоном , причем можно регулировать степень прозрачности. При уменьшении размеров png не происходит потери в качестве цвета.
Подытожим
gif — для анимации
jpeg — для фотографий
png — для иконок, кнопок, фонов, логотипов, скриншотов, чертежей, текстов, фотографий с прозрачным фоном
Вставка изображения в html-файл
Для добавления картинки на страницу используется тег <img> (от англ. image — изображение, картинка). Это одиночный тег, ему не нужен закрывающий. Внутри этого тега содержатся атрибуты.
Атрибут src (от англ. source — источник) указывает путь к файлу (место, где лежит изображение). Если картинка лежит у вас на компьютере (пока сайт только в процессе разработки) или на вашем сервере — используйте относительную ссылку. Если имидж из сети, тогда нужна абсолютная ссылка. Как это сделать читайте в статье «Ссылки».
При создании сайта с нуля советуем создать отдельную папку для хранения имиджей. Так вам будет проще управлять всеми файлами, когда ваш сайт разрастется.
Итак, чтобы подключить изображение к вашей веб-странице, нужно написать такой код:
Тег <img> HTML картинка
![]()
![]()
![]()
![]()
![]()
Тег <img> используется для вставки графического изображения (картинки) в HTML документ.
HTML тег <img> имеет два обязательных атрибута: src — адрес файла картинки и alt — альтернативный текст, который будет отображен, если картинка не может быть загружена. Также не лишним будет использование глобального атрибута title .
Изображение из тега <img> может быть ссылкой. Для этого нужно обвернуть тег <img> тегом ссылки <a> (см. пример ниже).
Синтаксис
Отображение в браузере

Пример использования <img> в HTML коде
Поддержка браузерами
| Тег | |||||
| <img> | Да | Да | Да | Да | Да |
Атрибуты
Альтернативный текст, который будет выведен, если картинка не будет загружена.
ismap
пусто
Логический атрибут. Указывает, что картинка является серверной (server-side) картой-изображением.
URL файла, где содержится детальное описание картинки.
Указывает URL файла картинки.
Указывает, что картинка является клиентской (client-side) картой-изображением.
Устаревшие атрибуты
Указанные ниже атрибуты не поддерживаются в HTML5. Используйте CSS вместо них.
Правило выравнивания картинки.
Ширина границ картинки.
Ширина горизонтальных отступов (пустое место слева и справа от картинки).
Ширина вертикальных отступов (пустое место сверху и снизу от картинки).

![]()
![]()
![]()
![]()
![]()
Отдельного урока по этой теме не делал.
Чтобы сделать отступ от изображения, вы можете использовать CSS-свойство margin (например, «margin: 15px;» — отступ 15 пикселей со всех сторон картинки, «margin-right: 10px;» — отступ 10 пикселей справа).
Границу можно сделать с помощью CSS-свойства border (например, «border: 1px solid black;» — черная линия шириной 1 пиксель).
Для выравнивания картинки есть много способов. Тут уже зависит от ваших потребностей. Для выравнивания по центру блока (по горизонтали), например, можете использовать CSS-правило: «text-align: center;» у родительского блока.