The <img>
tag is used to display images on a webpage.
It is a self-closing tag that requires a src
attribute, which
specifies the path to the image file, and an alt
attribute,
which provides an alternative text description of the image.
Here's a basic example of using the <img>
tag:
<img src="platypus.jpg" alt="A platypus swimming in water" />
This code will display the image located at platypus.jpg
with
a description that reads "A platypus swimming in water." If the image
cannot be displayed, the alt text will appear in its place, making it
important for accessibility.
The <figure>
element is used to group images with their
captions, making them easier to associate. You can include multiple images
in a figure or use it to wrap other types of media. The
<figcaption>
element provides a caption for the content
inside <figure>
.
As well as linking from your own computer, you can also use absolute links.
When specifying the src
attribute in an
<img>
tag, you can use either a relative path or an
absolute path:
src="images/platypus.jpg"
—
Points to an image in a folder called "images" relative to the current
file.
src="https://example.com/platypus.jpg"
— Points to an image
located at an external URL.
The width
and height
attributes allow you to set
the dimensions of an image in pixels, but it's often better to control the
size with CSS to keep your code clean. Avoid using these attributes if the
image is meant to be responsive.
You can also use CSS properties like max-width
and
height
to ensure your images resize correctly based on screen
size.
To make your images responsive, use the following CSS properties:
img {
max-width: 100%;
height: auto;
}
This will ensure that the image scales down to fit within its container without exceeding its original dimensions.
Always include an alt
attribute for every image. The text
should describe the content and function of the image. If an image is
purely decorative, you can use an empty alt attribute like this:
alt=""
. This tells screen readers to skip the image,
improving the accessibility of your site.