How to Add Images in HTML
Adding images to your website enhances its appearance and makes it more engaging. In HTML, the <img>
tag is used to display images. Let's walk through the basics of how to do this.
The Basic Syntax
The <img>
tag is self-closing, which means it doesn't require a closing tag. Here's the general syntax:
<img src="image-file-path" alt="alternative-text">
Attributes Explained:
- src: Specifies the path or URL of the image file.
- alt: Provides alternative text for the image. This text is displayed if the image cannot load and improves accessibility for screen readers.
To link from the homepage (index.html) to the About page(about.html), your code would look like this:
<a href="about.html">About Us</a>
Example: Adding an Image
Here's an example of adding an image to a webpage:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Adding Images</title>
</head>
<body>
<h1>Welcome to My Website</h1>
<img src="images/sunset.jpg" alt="A beautiful sunset over the ocean">
</body>
</html>
What Happens Here?
- The src attribute points to an image file namedsunset.jpg, which is stored in the images folder.
- The alt attribute describes the image as 'A beautiful sunset over the ocean.'
To link from the homepage (index.html) to the About page(about.html), your code would look like this:
<a href="about.html">About Us</a>
Types of Image Paths
You can use different types of paths for the src attribute:
1. Relative Path: Points to a file relative to the current file.
<img src="images/photo.jpg" alt="A photo">
2. Absolute Path: Points to the full URL of an image.
<img src="https://example.com/images/photo.jpg" alt="A photo">
">
Tips for Using Images
- Optimize File Sizes: Use tools to compress images for faster loading.
- Use Descriptive alt Text: This improves accessibility and helps with SEO.
- Responsive Images: Use CSS to make your images adjust to different screen sizes.