HTML Images
A guide to understanding how to use HTML images, including attributes like src, alt, title, width, height, lazy loading, and supported image formats.
In this guide, we'll cover how to use HTML images effectively, including common attributes and techniques like lazy loading and supported image formats.
Images are essential to enrich the content of your webpage. In HTML, the <img> tag is used to display images.
The <img> tag doesn't have a closing tag, and it's self-closing.
Example:
🖼️ Important Attributes for <img>
src: The source attribute, used to specify the path to the image.alt: The alt text provides a description of the image. It is essential for accessibility and appears if the image cannot be loaded.title: Provides additional information when the user hovers over the image.widthandheight: Specifies the width and height of the image (in pixels).
Example:
🛏️ Lazy Loading
Lazy loading is a technique that defers the loading of images until they are required (i.e., when they are about to enter the viewport). This improves the page's load time.
Example (using the loading="lazy" attribute):
This will load the image only when it is about to appear on the user's screen.
🖼️ Supported Image Formats
Different image formats are used for different purposes based on the required quality, file size, and browser compatibility. Below are some common image formats used in HTML:
- JPG: A widely used format for high-quality images with relatively small file sizes. Ideal for photographs.
- PNG: Supports transparent backgrounds and is ideal for graphics and logos.
- SVG: Scalable vector graphics, perfect for images that need to scale without losing quality, like logos or icons.
- WebP: A modern image format that provides superior compression and quality. It's supported in most modern browsers.
Example for different formats:
🧪 Try Yourself
✅ Conclusion
In this guide, we have covered the basic usage of the <img> tag, including how to define essential attributes like src, alt, width, height, and title. We've also discussed lazy loading, which optimizes page performance, and explored various image formats such as JPG, PNG, SVG, and WebP.
💡 Pro Tip: Always add alt text to your images for accessibility. It helps screen readers describe images to users with visual impairments.