<img> element is one of the first elements developers learn, and it’s used to embed images in web documents. It is an empty element and contains attributes only.
The primary purpose of the
<img> element is to enhance the visual appeal and interactivity of web pages by displaying images. It was created to address the growing need for presenting graphical content on the World Wide Web, which has evolved into a multimedia-rich environment.
The basic syntax of the
<img> element is as follows:
<img src="url/to/image.jpg" alt="alternative text">
Here is an example of how to use the
<img src="farm.jpg" alt="A beautiful farm landscape">
In the embedded demo here, you’ll see the first image (which is 500×500px by default) has burst beyond the boundaries of its containing
The second image, even though it has
height attributes set on the
<img> element, is fluid and neatly contained within its fixed parent element. The CSS needed for this is:
width: 100%; /* this makes the image width 100% of its containing element */
height: auto; /* some browsers need this to make sure the height stays in proportion to the width */
Lastly, the final image hasn’t been found by the browser, so a broken image icon is shown, along with the ALT (alternative) text.
<img> element supports global attributes and includes several additional attributes:
src: Specifies the image file’s web address.
alt: Provides alternative text for accessibility.
width: Sets image width.
height: Sets image height.
title: Adds a tooltip with extra information.
srcset: Offers responsive image options.
sizes: Helps choose the right image for the viewport.
crossorigin: Manages cross-origin image requests.
usemap: Links to server-side image maps.
ismap: Indicates server-side image map use.
referrerpolicy: Controls referrer information sent.
decoding: Optimizes image decoding.
loading: Controls image loading behavior.
fetchpriority: Provides hints for resource loading priority.
<img> element is empty and does not accept content or have closing tags.
Did You Know?
altattribute is important for accessibility, as it describes the image for those who cannot see it.
- You can actually style an image’s alt tag using CSS.
- If the
srcattribute is not present, the
<img>tag will be ignored.