The HTML <img>
tag is used to embed an image in a web page. Here's an in-depth explanation of the various attributes and usage of the <img>
tag:
Basic Syntax:
<img src="image.jpg" alt="Image description">
Attributes:
src: This attribute specifies the source (URL or file path) of the image you want to display.
alt: This attribute provides alternative text that is displayed if the image cannot be loaded or for accessibility purposes. It should describe the image's content.
Optional Attributes:
width: Specifies the width of the image in pixels or as a percentage of the parent container's width.
height: Specifies the height of the image in pixels or as a percentage of the parent container's height.
title: Adds a tooltip or additional information about the image when the user hovers over it.
class: Assigns a class name to the image for CSS styling.
id: Provides a unique identifier for the image.
style: Allows you to apply inline CSS styles to the image.
border: Sets the border size around the image in pixels.
Example Usage:
<img src="image.jpg" alt="Beautiful landscape" width="500" height="300">
Responsive Images: To make images responsive and adjust their size based on the screen or container, you can use CSS. Here's an example:
<style>
.responsive-img {
max-width: 100%;
height: auto;
}
</style>
<img src="image.jpg" alt="Responsive image" class="responsive-img">
Using Images as Links: You can also use an image as a link by wrapping the <img>
tag with an <a>
tag:
<a href="destination.html">
<img src="image.jpg" alt="Clickable image">
</a>
These are the key aspects of using the <img>
tag in HTML. Remember to provide appropriate alt
text for images, which improves accessibility and helps users understand the content even if the image fails to load.