Images make websites visually appealing and engaging. In HTML, images are added using the <img> tag, allowing you to display photos, illustrations, or icons on your web pages. This tutorial explains how to use images effectively, with clear examples, to help beginners create better websites.
The <img> tag is used to embed images in a webpage. It’s a self-closing tag, meaning it doesn’t need a closing tag like </img>. Images can be sourced from your local files or external URLs, and they enhance both the look and functionality of a site.
The basic structure of an image tag looks like this:
<img src="image.jpg" alt="Description of image">
Here’s what each part means:
Let’s explore different ways to use images in HTML.
If the image is stored on your server, use a relative or absolute path.
<img src="images/puppy.jpg" alt="A cute puppy">
This assumes "puppy.jpg" is in a folder named "images" in your project.
You can also link to images hosted online.
<img src="https://example.com/puppy.jpg" alt="A cute puppy">
Ensure you have permission to use external images to avoid copyright issues.
Wrap an <img> tag in an <a> tag to make the image clickable.
<a href="https://example.com">
<img src="logo.png" alt="Company logo">
</a>
Besides src and alt, here are important attributes to enhance images:
<img src="photo.jpg" alt="Landscape" width="300" height="200">
Note: Use CSS for responsive designs instead of hardcoding sizes.
<img src="photo.jpg" alt="Landscape" title="A beautiful sunset">
<img src="photo.jpg" alt="Landscape" loading="lazy">
To make your images effective and user-friendly:
max-width: 100%
).Beginners often make these errors:
Create a simple HTML file and experiment with adding images. Try different attributes and test how they display.
<!DOCTYPE html>
<html lang="en">
<body>
<img src="images/sample.jpg" alt="A beautiful flower" width="200" height="150">
</body>
</html>
By mastering the <img> tag and its attributes, you can create visually rich websites that engage users. Practice regularly to get comfortable!