<img>: The Image Embed element
The <img> HTML element embeds an image into the document.
Try it
The above example shows usage of the <img> element:
- The src attribute is required, and contains the path to the image you want to embed.
- The alt attribute holds a text description of the image, which isn’t mandatory but is incredibly useful for accessibility — screen readers read this description out to their users so they know what the image means. Alt text is also displayed on the page if the image can’t be loaded for some reason: for example, network errors, content blocking, or linkrot.
There are many other attributes to achieve various purposes:
-
/CORS control for security and privacy: see crossorigin and referrerpolicy .
- Use both width and height to set the intrinsic size of the image, allowing it to take up space before it loads, to mitigate content layout shifts.
- Responsive image hints with sizes and srcset (see also the <picture> element and our Responsive images tutorial).
Supported image formats
The HTML standard doesn’t list what image formats to support, so user agents may support different formats.
Note: The Image file type and format guide provides comprehensive information about image formats and their web browser support. This section is just a summary!
The image file formats that are most commonly used on the web are:
-
— Good choice for lossless animation sequences (GIF is less performant) — Good choice for both images and animated images due to high performance. — Good choice for simple images and animations. — Good choice for lossy compression of still images (currently the most popular). — Good choice for lossless compression of still images (slightly better quality than JPEG). — Vector image format. Use for images that must be drawn accurately at different sizes. — Excellent choice for both images and animated images
Formats like WebP and AVIF are recommended as they perform much better than PNG, JPEG, GIF for both still and animated images. WebP is widely supported while AVIF lacks support in Edge.
SVG remains the recommended format for images that must be drawn accurately at different sizes.
Image loading errors
If an error occurs while loading or rendering an image, and an onerror event handler has been set for the error event, that event handler will get called. This can happen in several situations, including:
- The src attribute is empty ( «» ) or null .
- The src URL is the same as the URL of the page the user is currently on.
- The image is corrupted in some way that prevents it from being loaded.
- The image’s metadata is corrupted in such a way that it’s impossible to retrieve its dimensions, and no dimensions were specified in the <img> element’s attributes.
- The image is in a format not supported by the user agent.
Attributes
This element includes the global attributes.
Defines an alternative text description of the image.
Note: Browsers do not always display images. There are a number of situations in which a browser might not display images, such as:
- Non-visual browsers (such as those used by people with visual impairments)
- The user chooses not to display images (saving bandwidth, privacy reasons)
- The image is invalid or an unsupported type
In these cases, the browser may replace the image with the text in the element’s alt attribute. For these reasons and others, provide a useful value for alt whenever possible.
Setting this attribute to an empty string ( alt=»» ) indicates that this image is not a key part of the content (it’s decoration or a tracking pixel), and that non-visual browsers may omit it from rendering. Visual browsers will also hide the broken image icon if the alt is empty and the image failed to display.
This attribute is also used when copying and pasting the image to text, or saving a linked image to a bookmark.
Indicates if the fetching of the image must be done using a CORS request. Image data from a CORS-enabled image returned from a CORS request can be reused in the <canvas> element without being marked «tainted».
If the crossorigin attribute is not specified, then a non-CORS request is sent (without the Origin request header), and the browser marks the image as tainted and restricts access to its image data, preventing its usage in <canvas> elements.
If the crossorigin attribute is specified, then a CORS request is sent (with the Origin request header); but if the server does not opt into allowing cross-origin access to the image data by the origin site (by not sending any Access-Control-Allow-Origin response header, or by not including the site’s origin in any Access-Control-Allow-Origin response header it does send), then the browser blocks the image from loading, and logs a CORS error to the devtools console.
A CORS request is sent with credentials omitted (that is, no cookies, X.509 certificates, or Authorization request header).
The CORS request is sent with any credentials included (that is, cookies, X.509 certificates, and the Authorization request header). If the server does not opt into sharing credentials with the origin site (by sending back the Access-Control-Allow-Credentials: true response header), then the browser marks the image as tainted and restricts access to its image data.
If the attribute has an invalid value, browsers handle it as if the anonymous value was used. See CORS settings attributes for additional information.
Provides an image decoding hint to the browser. Allowed values:
Decode the image synchronously, for atomic presentation with other content.
Decode the image asynchronously, to reduce delay in presenting other content.
Default: no preference for the decoding mode. The browser decides what is best for the user.
Marks the image for observation by the PerformanceElementTiming API. The value given becomes an identifier for the observed image element. See also the elementtiming attribute page.
Provides a hint of the relative priority to use when fetching the image. Allowed values:
Signals a high-priority fetch relative to other images.
Signals a low-priority fetch relative to other images.
Default: Signals automatic determination of fetch priority relative to other images.
The intrinsic height of the image, in pixels. Must be an integer without a unit.
Note: Including height and width enables the aspect ratio of the image to be calculated by the browser prior to the image being loaded. This aspect ratio is used to reserve the space needed to display the image, reducing or even preventing a layout shift when the image is downloaded and painted to the screen. Reducing layout shift is a major component of good user experience and web performance.
This Boolean attribute indicates that the image is part of a server-side map. If so, the coordinates where the user clicked on the image are sent to the server.
Note: This attribute is allowed only if the <img> element is a descendant of an <a> element with a valid href attribute. This gives users without pointing devices a fallback destination.
Indicates how the browser should load the image:
Loads the image immediately, regardless of whether or not the image is currently within the visible viewport (this is the default value).
Defers loading the image until it reaches a calculated distance from the viewport, as defined by the browser. The intent is to avoid the network and storage bandwidth needed to handle the image until it’s reasonably certain that it will be needed. This generally improves the performance of the content in most typical use cases.
Note: Loading is only deferred when JavaScript is enabled. This is an anti-tracking measure, because if a user agent supported lazy loading when scripting is disabled, it would still be possible for a site to track a user’s approximate scroll position throughout a session, by strategically placing images in a page’s markup such that a server can track how many images are requested and when.
A string indicating which referrer to use when fetching the resource:
- no-referrer : The Referer header will not be sent.
- no-referrer-when-downgrade : The Referer header will not be sent to origins without TLS (HTTPS).
- origin : The sent referrer will be limited to the origin of the referring page: its scheme, host, and port.
- origin-when-cross-origin : The referrer sent to other origins will be limited to the scheme, the host, and the port. Navigations on the same origin will still include the path.
- same-origin : A referrer will be sent for same origin, but cross-origin requests will contain no referrer information.
- strict-origin : Only send the origin of the document as the referrer when the protocol security level stays the same (HTTPS→HTTPS), but don’t send it to a less secure destination (HTTPS→HTTP).
- strict-origin-when-cross-origin (default): Send a full URL when performing a same-origin request, only send the origin when the protocol security level stays the same (HTTPS→HTTPS), and send no header to a less secure destination (HTTPS→HTTP).
- unsafe-url : The referrer will include the origin and the path (but not the fragment, password, or username). This value is unsafe, because it leaks origins and paths from TLS-protected resources to insecure origins.
One or more strings separated by commas, indicating a set of source sizes. Each source size consists of:
- A media condition. This must be omitted for the last item in the list.
- A source size value.
Media Conditions describe properties of the viewport, not of the image. For example, (max-height: 500px) 1000px proposes to use a source of 1000px width, if the viewport is not higher than 500px.
Source size values specify the intended display size of the image. User agents use the current source size to select one of the sources supplied by the srcset attribute, when those sources are described using width ( w ) descriptors. The selected source size affects the intrinsic size of the image (the image’s display size if no CSS styling is applied). If the srcset attribute is absent, or contains no values with a width descriptor, then the sizes attribute has no effect.
The image URL. Mandatory for the <img> element. On browsers supporting srcset , src is treated like a candidate image with a pixel density descriptor 1x , unless an image with this pixel density descriptor is already defined in srcset , or unless srcset contains w descriptors.
One or more strings separated by commas, indicating possible image sources for the user agent to use. Each string is composed of:
- A URL to an image
- Optionally, whitespace followed by one of:
- A width descriptor (a positive integer directly followed by w ). The width descriptor is divided by the source size given in the sizes attribute to calculate the effective pixel density.
- A pixel density descriptor (a positive floating point number directly followed by x ).
If no descriptor is specified, the source is assigned the default descriptor of 1x .
It is incorrect to mix width descriptors and pixel density descriptors in the same srcset attribute. Duplicate descriptors (for instance, two sources in the same srcset which are both described with 2x ) are also invalid.
If the srcset attribute uses width descriptors, the sizes attribute must also be present, or the srcset itself will be ignored.
The user agent selects any of the available sources at its discretion. This provides them with significant leeway to tailor their selection based on things like user preferences or bandwidth conditions. See our Responsive images tutorial for an example.
The intrinsic width of the image in pixels. Must be an integer without a unit.
The partial URL (starting with # ) of an image map associated with the element.
Note: You cannot use this attribute if the <img> element is inside an <a> or <button> element.
Deprecated attributes
Aligns the image with its surrounding context. Use the float and/or vertical-align CSS properties instead of this attribute. Allowed values:
Equivalent to vertical-align: top or vertical-align: text-top
Equivalent to vertical-align: -moz-middle-with-baseline
The default, equivalent to vertical-align: unset or vertical-align: initial
Equivalent to float: left
Equivalent to float: right
The width of a border around the image. Use the border CSS property instead.
The number of pixels of white space on the left and right of the image. Use the margin CSS property instead.
A link to a more detailed description of the image. Possible values are a URL or an element id .
Note: This attribute is mentioned in the latest W3C version, HTML 5.2, but has been removed from the WHATWG’s HTML Living Standard. It has an uncertain future; authors should use a WAI-ARIA alternative such as aria-describedby or aria-details .
A name for the element. Use the id attribute instead.
The number of pixels of white space above and below the image. Use the margin CSS property instead.
Styling with CSS
<img> is a replaced element; it has a display value of inline by default, but its default dimensions are defined by the embedded image’s intrinsic values, like it were inline-block . You can set properties like border / border-radius , padding / margin , width , height , etc. on an image.
<img> has no baseline, so when images are used in an inline formatting context with vertical-align : baseline , the bottom of the image will be placed on the text baseline.
You can use the object-position property to position the image within the element’s box, and the object-fit property to adjust the sizing of the image within the box (for example, whether the image should fit the box or fill it even if clipping is required).
Depending on its type, an image may have an intrinsic width and height. For some image types, however, intrinsic dimensions are unnecessary. SVG images, for instance, have no intrinsic dimensions if their root <svg> element doesn’t have a width or height set on it.
Examples
Alternative text
The following example embeds an image into the page and includes alternative text for accessibility.
Image link
This example builds upon the previous one, showing how to turn the image into a link. To do so, nest the <img> tag inside the <a> . You should make the alternative text describe the resource the link is pointing to, as if you were using a text link instead.
Using the srcset attribute
In this example we include a srcset attribute with a reference to a high-resolution version of the logo; this will be loaded instead of the src image on high-resolution devices. The image referenced in the src attribute is counted as a 1x candidate in user agents that support srcset .
Using the srcset and sizes attributes
The src attribute is ignored in user agents that support srcset when w descriptors are included. When the (max-width: 600px) media condition matches, the 200 pixel-wide image will load (it is the one that matches 200px most closely), otherwise the other image will load.
Note: To see the resizing in action, view the example on a separate page, so you can actually resize the content area.
Security and privacy concerns
Although <img> elements have innocent uses, they can have undesirable consequences for user security and privacy. See Referer header: privacy and security concerns for more information and mitigations.
Accessibility concerns
Authoring meaningful alternate descriptions
An alt attribute’s value should clearly and concisely describe the image’s content. It should not describe the presence of the image itself or the file name of the image. If the alt attribute is purposefully left off because the image has no textual equivalent, consider alternate methods to present what the image is trying to communicate.
When an alt attribute is not present on an image, some screen readers may announce the image’s file name instead. This can be a confusing experience if the file name isn’t representative of the image’s contents.
Identifying SVG as an image
Due to a VoiceOver bug, VoiceOver does not correctly announce SVG images as images. Include role=»img» to all <img> elements with SVG source files to ensure assistive technologies correctly announce the SVG as image content.
The title attribute
The title attribute is not an acceptable substitute for the alt attribute. Additionally, avoid duplicating the alt attribute’s value in a title attribute declared on the same image. Doing so may cause some screen readers to announce the description twice, creating a confusing experience.
The title attribute should also not be used as supplemental captioning information to accompany an image’s alt description. If an image needs a caption, use the figure and figcaption elements.
The value of the title attribute is usually presented to the user as a tooltip, which appears shortly after the cursor stops moving over the image. While this can provide additional information to the user, you should not assume that the user will ever see it: the user may only have keyboard or touchscreen. If you have information that’s particularly important or valuable for the user, present it inline using one of the methods mentioned above instead of using title .
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
В HTML изображения определяются тегом <img> .
Тег <img> пуст, он содержит только атрибуты и не имеет закрывающего тега.
Атрибут src задает URL-адрес (веб-адрес) изображения:
Атрибут ALT
Атрибут alt предоставляет альтернативный текст для изображения, если пользователь по какой-либо причине не может его просмотреть (из-за медленного соединения, ошибки в атрибуте src или если пользователь использует средство чтения с экрана).
Значение атрибута alt должно описывать изображение:
Пример
Если обозреватель не может найти изображение, будет отображено значение атрибута alt :
Пример
Примечание: Атрибут alt является обязательным. Веб-страница не будет корректно проверяться без нее.
Размер изображения-ширина и высота
Для указания ширины и высоты изображения можно использовать атрибут style .
Пример
Кроме того, можно использовать атрибуты width и height :
Пример
Атрибуты width и height всегда определяют ширину и высоту изображения в пикселях.
Примечание: Всегда указывайте ширину и высоту изображения. Если ширина и высота не указаны, страница может мерцать во время загрузки изображения.
Ширина и высота, или стиль?
Атрибуты width , height и style действительны в HTML5.
Однако рекомендуется использовать атрибут style . Это предотвращает изменение размера изображений в таблицах стилей:
Пример
Изображения в другой папке
Если не указано, обозреватель ожидает найти изображение в той же папке, что и веб-страница.
Тем не менее, он является общим для хранения изображений в вложенной папке. Затем необходимо включить имя папки в атрибут src :
Пример
Изображения на другом сервере
Некоторые веб-узлы хранят свои изображения на серверах образов.
На самом деле, вы можете получить доступ к изображениям с любого веб-адреса в мире:
Пример
Дополнительные сведения о путях к файлам можно прочитать в разделе пути к файлам HTML.
Анимированные изображения
HTML позволяет анимированные GIF:
Пример
Изображение как ссылка
Чтобы использовать изображение в качестве ссылки, поместите тег <img> внутрь тега <a> :
Пример
Примечание: border:0; добавляется для предотвращения IE9 (и более ранних) от отображения границы вокруг изображения (когда изображение является ссылкой).
Плавающее изображение
Используйте свойство CSS float , чтобы изображение поплыло вправо или влево от текста:
Пример
<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>
Совет: Чтобы узнать больше о CSS float, прочитайте наш Справочник по CSS float.
Графические карты
Тег <map> определяет изображение-карту. Изображение-карта представляет собой изображение с щелчком области.
На картинке ниже, нажмите на компьютер, Телефон, или чашку кофе:
Пример
Атрибут name тега <map> связан с атрибутом usemap <img> и создает связь между изображением и картой.
Элемент <map> содержит несколько тегов <area> , определяющих области, на которые вы щелкнули на карте изображения.
Фоновое изображение
Чтобы добавить фоновое изображение в элемент HTML, используйте свойство CSS background-image :
Пример
Чтобы добавить фоновое изображение на веб-страницу, укажите свойство Background-Image элементу Body:
Примере
Чтобы добавить фоновое изображение для абзаца, укажите свойство Background-Image в элементе P:
Чтобы узнать больше о фоновых изображениях, изучите наши CSS Background Справочник.
Элемент <picture>
HTML5 ввел элемент <picture> , чтобы добавить больше гибкости при указании ресурсов изображения.
Элемент <picture> содержит ряд элементов <source>, каждый из которых ссылается на различные источники изображения. Таким образом, обозреватель может выбрать изображение, которое наилучшим образом соответствует текущему виду и/или устройству.
Каждый элемент <source> имеет атрибуты, описывающие, когда их изображение является наиболее подходящим.
Обозреватель будет использовать первый элемент <source> с совпадающими значениями атрибутов и игнорировать любые следующие элементы <source> .
Пример
Показать одно изображение, если окно обозревателя (видовой экран) не менее 650 пикселей, а другое изображение, если нет, но больше, чем 465 пикселей.
Примечание: Всегда указывайте элемент <img> в качестве последнего дочернего элемента элемента <picture> . Элемент <img> используется обозревателями, которые не поддерживают элемент <picture> , или если ни один из тегов <source> не соответствует.
Читатели экрана HTML
Программа чтения с экрана — это программное обеспечение, которое читает HTML-код, преобразует текст и позволяет пользователю прослушивать содержимое. Читатели экрана полезны для людей, которые слепы, слабовидящих или обучения инвалидов.
Справка
- Используйте элемент HTML <img> для определения изображения
- Используйте атрибут HTML src для определения URL-адреса изображения
- Используйте атрибут HTML alt для определения альтернативного текста для изображения, если он не может быть отображен
- Используйте атрибуты HTML width и height для определения размера изображения
- Используйте свойства CSS width и height для определения размера изображения (в качестве альтернативы)
- Используйте свойство CSS float , чтобы позволить изображению поплавок
- Используйте элемент HTML <map> для определения изображения-карты
- Используйте элемент HTML <area> для определения областей щелчка на карте изображения
- Используйте атрибут usemap элемента HTML <img> , чтобы указать на карту изображения
- Используйте элемент HTML <picture> для отображения различных изображений для различных устройств
Примечание: Загрузка изображений занимает время. Большие изображения могут замедлить вашу страницу. Используйте изображения тщательно.
Как сделать картинку ссылкой в html
Для вывода изображений в html используется тег <img>. Выглядит это таким образом:
Для того чтобы создать ссылку используется тег <a>. Таким вот образом:
Чтобы картинку сделать ссылкой, необходимо всего лишь объединить эти два тега.
Тег картинки вставляется внутрь тега ссылки. Таким образом, картинка работает как ссылка, если на нее навести курсор мыши и нажать, произойдет переход по ссылке.