HTML Guide for img
A single <img> element is used to embed an image, so adding the img role to it is redundant.
The ARIA img role can be used to identify multiple elements inside page content that should be considered as a single image. These elements could be images, code snippets, text, emojis, or other content that can be combined to deliver information in a visual manner, for example:
<div role="img" aria-label="Description of the overall image">
<img src="graphic1.png" alt="">
<img src="graphic2.png">
</div>
The deprecated property longdesc on img elements was used in HTML4 to specify the URL of a text or HTML file which contained a long-form description of the image. This could be used to provide optional added details beyond the short description provided in the title or alt attributes.
Here’s an example from HTML4:
<img
src="cat.jpg"
alt="Smiling Cat"
longdesc="image-descriptions/smiling-cat.html" />
This, however, is no longer valid in HTML5 and can be converted to the following instead:
<a href="image-descriptions/smiling-cat.html">
<img src="cat.jpg" alt="Smiling Cat" />
</a>
The warning regarding the use of the name attribute on the img element arises because the name attribute is considered obsolete in modern HTML. Historically, name was used to identify form controls and some other elements, but now it’s replaced by more standardized attributes like id.
To resolve this issue, replace the name attribute with the id attribute. The id attribute provides a unique identifier for the element within the document, which can be utilized for styling, scripting, or linking using fragment identifiers.
Here is an example of how to make this change:
HTML with obsolete name attribute:
<img src="example.jpg" name="myImage" alt="Descriptive text">
Updated HTML using the id attribute:
<img src="example.jpg" id="myImage" alt="Descriptive text">
In this modification:
- The name="myImage" is replaced with id="myImage".
- The remaining attributes like src and alt are retained for specifying the image source and providing alternative text, respectively.
The id attribute should be unique within the document, which ensures that JavaScript or CSS can target the element efficiently.
Check the HTMLImageElement.srcset guide to learn about the correct usage of the srcset and sizes attributes.