Adding Images in HTML
Adding images to an HTML document is a straightforward process. The <img>
tag is used to embed an image into the web page. The src
attribute of the <img>
tag specifies the URL or file path of the image you want to display.
Here's the basic syntax for adding an image in HTML:
<img src="image_path_or_url" alt="Image Description" />
src
: This attribute specifies the location of the image file, either a relative path (e.g.,"images/logo.jpg"
) or an absolute URL (e.g.,"https://example.com/logo.png"
).alt
: This attribute provides an alternate text description of the image, which is displayed if the image cannot be loaded or for accessibility purposes.
For example, to add an image of a cat to your HTML page, you can use the following code:
<img src="cat.jpg" alt="A cute cat" />
This will display the image of the cat on the web page.
Image Formats
HTML supports various image formats, including:
- JPEG (
.jpg
or.jpeg
): Commonly used for photographs and complex images. - PNG (
.png
): Supports transparency and is suitable for graphics with text or simple illustrations. - GIF (
.gif
): Supports animation and is often used for simple graphics or icons. - SVG (
.svg
): A vector-based format that can be scaled without losing quality.
The choice of image format depends on the type of image and the desired quality and file size.
Sizing Images
You can control the size of the image by setting the width
and height
attributes of the <img>
tag. For example:
<img src="cat.jpg" alt="A cute cat" width="400" height="300" />
This will display the image with a width of 400 pixels and a height of 300 pixels.
Alternatively, you can also use CSS to set the size of the image:
<img src="cat.jpg" alt="A cute cat" style="width: 400px; height: 300px;" />
This approach provides more flexibility in controlling the image size.
Responsive Images
To ensure that images adapt to different screen sizes and devices, you can use responsive image techniques, such as the srcset
attribute or the <picture>
element. These allow you to provide multiple image sources, and the browser will automatically select the most appropriate one based on the user's device and screen size.
Here's an example using the srcset
attribute:
<img
src="cat-small.jpg"
srcset="cat-small.jpg 480w, cat-medium.jpg 768w, cat-large.jpg 1024w"
sizes="(max-width: 480px) 100vw, (max-width: 768px) 50vw, 33vw"
alt="A cute cat"
/>
In this example, the browser will choose the most appropriate image source based on the user's screen width.
By following these steps, you can easily add images to your HTML documents and ensure they are displayed correctly across different devices and screen sizes.