img Tag
The <img>
tag is used to insert images into a web page.
The key attributes for the img tag are src
, alt
, width
, and height
.
src
A required attribute that specifies the URL (address) of the image. The URL can point to an image within the same website or an image provided by an external website. Without the src attribute, the <img>
tag will not display an image.
<img src="https://example.com/myimage.jpg" />
alt
An attribute that specifies the alternative text for an image. It is used when the image fails to load or for providing screen readers for visually impaired users with "alternative text". Although it is not a mandatory attribute, it is essential for SEO (Search Engine Optimization).
<img src="https://picsum.photos/300" alt="Ocean view at sunset" />
width
and height
These attributes specify the width and height of an image, with the default unit being pixels (px). Pixels refer to individual points on the screen based on resolution. If width and height are not specified, the image will be displayed in its original size.
<img src="https://picsum.photos/300" width="300" height="200" />
How to Use the img Tag
- Specifying the src and alt attributes
<img src="https://picsum.photos/300" alt="Profile picture" />
- Specifying the width and height to set image size
<img
src="https://picsum.photos/300"
alt="Random image"
width="200"
height="150"
/>
Summary of the img Tag
-
Use the
src
attribute to specify the URL (address) of the image. -
The
alt
attribute provides a description of the image or the text to display if the image does not show. -
Use the
width
andheight
attributes to control the size of the image.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.