HTML Images
HTML <img>
Tag Tutorial by CodesWithPankaj
<img>
Tag Tutorial by CodesWithPankajThe HTML <img>
tag is used to display images on a webpage. It’s an empty tag (self-closing), meaning it doesn’t need a closing tag. The <img>
tag is very flexible and has several attributes to help you control the image display, size, description, and loading.
1. Basic Structure of <img>
Tag
<img>
TagThe <img>
tag has a basic structure:
src
(source): Specifies the path (URL) to the image file.alt
(alternative text): Provides a text description for the image, important for accessibility (e.g., screen readers) and in case the image doesn’t load.
Example 1: Adding a Simple Image
In this example:
src
points to the URL of the image.alt
describes the image as "CodesWithPankaj Logo."
2. Setting Image Size with width
and height
width
and height
You can control the display size of an image using the width
and height
attributes. Both accept values in pixels or percentages.
Here:
width="200"
sets the width of the image to 200 pixels.height="100"
sets the height to 100 pixels.
Note: Avoid distorting the image by setting width and height in different proportions than the original.
3. Using title
Attribute for Tooltips
title
Attribute for TooltipsThe title
attribute displays a tooltip when the user hovers over the image.
4. Linking Images
To make an image clickable (like a link), wrap the <img>
tag inside an <a>
tag.
Here:
When users click on the image, they’ll be taken to "https://www.codeswithpankaj.com".
5. Image Alignment with CSS
To align images on the webpage, it’s common to use CSS instead of HTML attributes like align
. Here’s an example using CSS:
This code:
Aligns the image to the right.
Adds a 10-pixel margin around the image.
6. Responsive Images with CSS
To make images responsive (adjusting to different screen sizes), you can use the CSS max-width
property.
max-width: 100%;
limits the image width to the container width.height: auto;
maintains the image’s original aspect ratio.
7. Lazy Loading Images
Lazy loading delays loading of images until they’re needed, improving page load speed. You can enable this with the loading="lazy"
attribute.
8. Full Example of HTML Document with Images
Here’s a complete HTML document demonstrating different ways to use the <img>
tag:
Summary
This tutorial covers the essential attributes and methods to work with images in HTML. By using the <img>
tag effectively, you can enhance your web pages with images that are accessible, responsive, and optimized. Practice with these examples, and create a visually engaging website with CodesWithPankaj!
Last updated