12. HTML Images
Images play a crucial role in web design by making content more engaging and visually appealing. In HTML, the <img>
tag is used to embed images within a page.
What Are HTML Images?
HTML images are used to display visual content on web pages. The <img>
tag is an empty tag that requires the src
attribute to specify the image source and the alt
attribute for alternative text, which describes the image in case it doesn't load or for accessibility purposes.
HTML <img>
Tag
The <img>
tag is used to embed images in HTML. It has several important attributes:
- src: Specifies the image source (URL).
- alt: Provides alternative text for accessibility and when the image cannot be displayed.
- width: Specifies the width of the image (in pixels).
- height: Specifies the height of the image (in pixels).
Example: Basic Image
Here is how you can add a basic image to a webpage:
<img src="example.jpg" alt="A sample image">
Using Image Width and Height
You can also specify the width and height of an image to control its display size:
<img src="example.jpg" alt="A sample image" width="300" height="200">
Responsive Images
For responsive design, you can make images scale based on the container size by setting the width
to "100%" and omitting the height
attribute:
<img src="example.jpg" alt="A sample image" width="100%">
Using Image with Links
Images can be used as links. When the user clicks on the image, they will be redirected to the target URL:
<a href="https://www.example.com">
<img src="example.jpg" alt="Example Image">
</a>
Image Accessibility
It is important to provide an alt
attribute with a brief description of the image, as this helps screen readers for visually impaired users:
<img src="example.jpg" alt="A picture of a beautiful sunset">
Image Formats
There are various image formats that you can use in HTML, including:
- JPEG: Ideal for photos and images with gradients.
- PNG: Best for images with transparency.
- GIF: Suitable for simple graphics and animations.
- SVG: Scalable vector graphics used for vector images and logos.
Best Practices for Using Images
- Optimize images to reduce their file size without compromising quality, to improve page load speed.
- Always include the
alt
attribute for accessibility. - Use responsive images to ensure they look good on all screen sizes.
- Choose the right image format based on the type of image (e.g., use PNG for logos, JPEG for photos).
Conclusion
Images are a powerful tool for enhancing the visual appeal of a website. By using the <img>
tag properly, you can ensure that your images are accessible, responsive, and optimized for the best performance.
In the next lesson, we will discuss HTML Lists and how to organize content using unordered and ordered lists.