HTML Images
Images are an essential part of web design, helping to enhance the user experience by making content visually appealing. In HTML, the <img>
tag is used to display images on a webpage. This guide will walk you through adding and resizing images in HTML, along with a comprehensive table explaining the important attributes of the <img>
tag.
Adding an Image in HTML
To add an image to your webpage, use the <img>
tag. The basic syntax looks like this:
<img src="image.jpg" alt="Description of image">
Explanation:
src
: Specifies the path to the image file.alt
: Provides alternative text for screen readers and displays if the image cannot be loaded.
Example:
<img src="https://example.com/nature.jpg" alt="Beautiful nature scenery">
This code will display an image from the given URL.
Resizing Images in HTML
You can resize an image using HTML attributes (width
and height
) or CSS.
Using HTML Attributes:
<img src="image.jpg" alt="Resized Image" width="300" height="200">
This sets the image width to 300 pixels and height to 200 pixels.
Using CSS for Resizing:
<style>
img {
width: 100%;
max-width: 500px;
height: auto;
}
</style>
<img src="image.jpg" alt="Responsive Image">
This CSS ensures the image resizes proportionally while staying within a maximum width of 500 pixels.
HTML <img>
Tag Attributes
The following table lists common <img>
attributes and their functions:
Attribute | Description |
---|---|
src |
Specifies the image source (URL or file path). |
alt |
Provides alternative text for the image. |
width |
Defines the width of the image (in pixels or %). |
height |
Defines the height of the image (in pixels or %). |
title |
Adds a tooltip when hovering over the image. |
loading |
Specifies lazy loading (lazy , eager ). |
style |
Allows inline CSS styles like width and height . |
Best Practices for Using Images in HTML
- Use descriptive alt text for accessibility and SEO.
- Optimize image sizes to improve page load speed.
- Use responsive images to ensure they look good on all devices.
- Choose the right format (JPEG for photos, PNG for transparent images, SVG for icons).
Conclusion
Using images effectively in HTML enhances your website’s appeal and usability. By understanding the <img>
tag and its attributes, you can efficiently add, resize, and optimize images for better performance and accessibility.