HTML Images
HTML <img> Tag
The <img> tag is used to embed images in an HTML document. It is a self-closing tag, meaning it doesn't need a closing tag.
Basic Syntax
<img src="image.jpg" alt="Description of the image">
Important Attributes
- src: Specifies the path or URL of the image (Required)
- alt: Provides alternative text if the image cannot be displayed (Important for accessibility)
- width and height: Set the image dimensions
- title: Shows text when hovering over the image
- loading="lazy": Delays loading of off-screen images for better performance
- srcset: Provides multiple image sources for different screen resolutions
- sizes: Specifies image display sizes for different viewports
Example: Local Image
<img src="images/photo.jpg" alt="My Photo">
Example: Image from URL
<img src="https://example.com/image.jpg" alt="Example Image">
Example: With Width and Height
<img src="image.jpg" alt="Resized Image" width="300" height="200">
Example: Responsive Image
<img src="responsive.jpg" alt="Responsive Design" style="width: 100%; height: auto;">
Example: Lazy Loading
<img src="large-image.jpg" alt="Lazy Image" loading="lazy">
Example: Modern Responsive Image with srcset
<img src="image-800.jpg"
srcset="image-400.jpg 400w,
image-800.jpg 800w,
image-1200.jpg 1200w"
sizes="(max-width: 600px) 400px,
(max-width: 1000px) 800px,
1200px"
alt="Responsive image example">
Best Practices
- Always include the alt attribute for accessibility
- Specify both width and height to prevent layout shifts
- Use loading="lazy" for below-the-fold images
- Optimize images for web before uploading
- Use modern formats like WebP when possible
- Implement responsive images with srcset and sizes
- Consider using the picture element for art direction
- Add title attribute for additional context when needed