The correct HTML tag for inserting an image is the <img>
tag.
The HTML <img> tag is used to embed an image in a web page. It's important to understand, as noted in the reference, that images are not technically inserted into a web page; rather, images are linked to web pages. The <img> tag creates a holding space for the referenced image. Crucially, the <img> tag is empty, meaning it contains attributes only, and does not have a closing tag.
Essential Image Attributes
To use the <img>
tag effectively and correctly, two attributes are mandatory:
src
: Specifies the path to the image file. This is where you tell the browser where to find the image.alt
: Provides alternative text for the image. This text is displayed if the image cannot be loaded, and it is essential for accessibility (used by screen readers) and SEO.
Basic Example
Here's the simplest form of the <img>
tag with the required attributes:
<img src="image.jpg" alt="Description of the image">
In this example:
src="image.jpg"
points to the image file named "image.jpg".alt="Description of the image"
provides a descriptive text alternative.
Common <img>
Tag Attributes
While src
and alt
are essential, other attributes offer control over presentation and behavior.
Attribute Table
Attribute | Description | Example |
---|---|---|
src |
Specifies the path (URL) to the image. (Required) | src="path/to/image.png" |
alt |
Specifies an alternative text for the image. (Required) | alt="A descriptive text" |
width |
Specifies the width of the image in pixels or percentage. | width="500" or width="50%" |
height |
Specifies the height of the image in pixels or percentage. | height="300" or height="auto" |
title |
Specifies extra information about the image (shown as a tooltip on hover). | title="More details" |
loading |
Specifies how the browser should load the image ("lazy" or "eager" ). |
loading="lazy" |
Using Width and Height
Specifying width
and height
attributes can help prevent layout shifts while the page loads, as the browser reserves space for the image. However, for responsive design, CSS is often preferred to control image dimensions.
<img src="another-image.gif" alt="Another image example" width="400" height="250">
Best Practices for Images
- Always include the
alt
attribute. - Use appropriate image formats (JPEG, PNG, GIF, SVG, WebP).
- Optimize image file sizes for faster loading.
- For complex layouts or effects, consider using CSS background images.
- Ensure image paths in the
src
attribute are correct.
In summary, the core HTML for displaying an image is the simple, empty <img>
tag, relying entirely on its attributes, primarily src
and alt
, to link and describe the image content.