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
Эта серия мануалов поможет вам создать и настроить веб-сайт с помощью HTML, стандартного языка разметки, используемого для отображения документов в браузере. Для работы с этими мануалами не требуется предварительный опыт программирования.
В результате выполнения этой серии у вас будет веб-сайт, готовый к развертыванию в облаке, также вы получите базовые знания HTML. Умение писать HTML – хорошая основа для изучения более сложных аспектов веб-разработки, таких как CSS и JavaScript.
Примечание: Найти все мануалы этой серии можно по тегу html-practice.
В этом мануале вы узнаете, как добавлять изображения на веб-сайт с помощью HTML. Мы также покажем, как добавлять alt-текст к изображениям, чтобы сделать их доступными для посетителей, использующих скринридеры.
Изображения добавляются в HTML-документ с помощью элемента <img>. Для элемента <img> требуется атрибут src, который определяет расположение файла, где хранится изображение. Элемент изображения записывается так:
Обратите внимание, что у элемента <img> нет закрывающего тега </img>. Чтобы попробовать добавить элемент <img>, загрузите для примера наш логотип и поместите его в каталог своего проекта html-practice.
Чтобы загрузить изображение, перейдите по ссылке и нажмите CTRL+левая кнопка мыши (на Mac) или правая кнопка мыши (на Windows) на изображении и выберите «Сохранить изображение как», а затем сохраните его как logo.svg в каталог вашего проекта.
Затем удалите содержимое вашего файла index.html и вставьте в него строку <img src = ”Image_Location”>.
Примечание: Если вы не работали с этой серией мануалов последовательно, рекомендуем обратиться к статье Подготовка HTML-проекта.
Затем скопируйте путь к файлу изображения и замените Image_Location расположением вашего сохраненного изображения. Если вы используете текстовый редактор Visual Studio Code, вы можете скопировать путь к файлу, нажав CTRL + левая кнопка мыши (на Mac) или правая кнопка мыши (в Windows) по файлу изображения logo.svg в левой панели, после чего выбрав «Copy Path».
Примечание: Убедитесь, что вы скопировали относительный путь, а не абсолютный (или полный) путь к файлу изображения. Относительный путь отображает расположение файла относительно текущего рабочего каталога, а абсолютный показывает расположение файла относительно корневого каталога. В этом тестовом случае работать будут оба пути, однако если бы вы решили загрузить сайт в Интернет, сработал бы только относительный путь. Поскольку конечная цель этой серии мануалов – создать веб-сайт, который можно разместить в интернете, мы будем использовать относительные пути при добавлении элементов <img> в документ.
Сохраните файл index.html и перезагрузите его в браузере. Вы должны получить страницу с логотипом.
Технически в качестве путей к файлам вы также можете использовать ссылки на изображения, размещенные в интернете. Чтобы понять, как это работает, попробуйте заменить относительный путь изображения ссылкой на наш логотип:
Сохраните файл и перезагрузите его в браузере. Изображение должно по-прежнему загружаться, но на этот раз оно загружается из его сетевого расположения, а не из локального каталога проекта. Ради эксперимента попробуйте добавить ссылки на другие изображения из сети с помощью атрибута src в теге <img>.
Все же при создании веб-сайта обычно рекомендуется размещать изображения в каталоге своего проекта, чтобы обеспечить устойчивость сайта. Если изображение, загруженное по ссылке из интернета, будет удалено или перемещено, оно больше не будет отображаться на вашем сайте.
Альтернативный текст для скринридеров
HTML позволяет добавлять альтернативный текст к изображениям, чтобы сделать сайт доступным для посетителей, использующих программы для озвучивания написанного на экране текста. Такой alt-текст должен описывать изображение. Он добавляется атрибутом alt:
<img src=»https://www.8host.com/blog/wp-content/themes/wp-8host-new/img/logo.svg» alt=»This is an 8host logo, which consists of black 8 and host in front of a blue cloud.» >
Теперь вы знаете, как вставлять изображения в свой HTML-документ и как добавлять alt-текст для скринридеров. Если вам интересно узнать, как изменить размер и стиль изображения, следите за руководствами этой серии. В следующем руководстве мы покажем, как добавлять ссылки в документ HTML.
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, как вставить картинку
Чтобы вставить картинку в HTML документ, используют тег <image> . У этого тега — два ключевых атрибута:
- src — определяет путь к файлу картинки.
- alt — устанавливает альтернативный текст. Он будет отображаться на странице, если картинка окажется недоступна и браузер не сможет ее показать пользователю.
Как использовать локальную картинку с сервера
Если картинка, которую ты хочешь использовать лежит на том же сервере, что и HTML документ, то можно указать относительный путь.
Как вставить картинку в HTML по URL ссылке
Бывает, что картинка находится на удаленном сервере и у тебя есть только ссылка на нее. Тогда ты можешь использовать эту ссылку как значение атрибута src .
Как изменить ширину и высоту картинки в HTML
Все что связано со стилизацией картинки, можно сделать с помощью CSS. Например, если мы хотим растянуть картинку по всей ширине экрана (или родительского контейнера), мы можем сделать так:
Но такой подход повлияет на все картинки на сайте.
Если тебе нужно изменить размеры только одной картинки, то можно добавить ей id .
И сделать CSS селектор по этому id .
Использование атрибутов width и height
Кроме CSS, изменить размер картинки в HTML можно добавив атрибуты width и height просто к тегу <image> .