To insert an image in HTML, you have to use the <img> tag, which is designed specifically for embedding images in web pages. Below is a comprehensive guide on how to use this tag properly, including key attributes, file paths, and best practices.
Basic Syntax of the <img> Tag
The fundamental way to add an image is:
<img src="image.jpg" alt="Description of image">
Where –
- src: Specifies the path or URL to your image file.
- alt: Provides alternative text displayed if the image cannot load (important for accessibility and SEO).
Note: The <img> tag in HTML is self-closing and does not require a closing tag.
Example
Suppose your image is named logo.png
and is in the same directory as your HTML file:
<img src="logo.png" alt="Company Logo">
If the image is stored in a subfolder called images, use:
<img src="images/logo.png" alt="Company Logo">
This relative path points to the location of your image based on your HTML file’s location.
Adding Size and Title Attributes
You can set the width and height to control your image’s display size. The title attribute shows a tooltip when users hover over the image:
<img src="images/photo.jpg" alt="Team Photo" width="300" height="200" title="Our Team">
- width and height: Specify dimensions in pixels.
- title: Shows extra info on hover (optional).
Using Absolute URL
To load an image from another website, use its full URL:
<img src="https://example.com/images/pic.jpg" alt="Online Picture">
Note: Make sure you have permission to use externally hosted images.
Making the Image a Link
To make your image clickable, wrap it in an <a>
(anchor) tag:
<a href="https://www.example.com">
<img src="logo.png" alt="Visit Our Site">
</a>
This creates a linked image where users can click.
Accessibility and Best Practices
- Always include alt text describing the image. This improves accessibility for screen readers and provides context if the image fails to load.
- Specify width and height to prevent page layout shifts while loading.
- Organize images in folders (e.g.,
/images
) to keep your project structured.
Complete HTML Code
<!DOCTYPE html> <html> <head> <title>How to Insert Image in HTML</title> </head> <body> <h2>Inserting an Image Example</h2> <p>This is how you insert an image in HTML:</p> <img src="images/example.jpg" alt="Sample Image" width="400" height="300"> </body> </html>
This example assumes the image file example.jpg
is inside a folder named images
.
Summary:
- Use the
<img>
tag for adding images. - Define the image location with the
src
attribute and its description withalt
. - Use optional
width
,height
, andtitle
attributes for better control and accessibility. - Organize images neatly for easier project management.
By following these steps, you ensure your images display correctly, load efficiently, and are accessible to all users.