<img>
The image tag

The HTML <img> tag is used to embed images in a web page. It is a self-closing (void) element, meaning it does not have a closing tag. The <img> tag is essential for adding visual content to web pages and supports various attributes for customization.

basic syntax

img src="image.jpg" alt="Description of the image">
  • src (Source): Specifies the image file location (URL or relative path).
  • alt (Alternative text): Provides descriptive text if the image fails to load, improving accessibility and SEO.
  • Common Attributes of the <img> Tag

    Setting Image Dimensions

    You can define the width and height in pixels or percentages.

    <img src="photo.jpg" alt="A scenic view" width="300" height="200">

    Best practice: Use CSS (max-width: 100%) instead of fixed widths to make images responsive.

    Responsive Images with srcset

    The srcset attribute allows browsers to load different images based on screen size, improving performance.

    img src="default.jpg" srcset="small.jpg 480w, medium.jpg 1024w, large.jpg 1920w" sizes=" (max-width: 600px) 480px, (max-width: 1200px) 1024px, 1920px" alt="A mountain landscape">

    The browser selects the best image based on device resolution.

    Using loading="lazy" for Performance

    The loading="lazy" attribute defers image loading until it's needed, improving page speed.

    <img src="nature.jpg" alt="Beautiful nature" loading="lazy">

    Making Images Clickable

    You can wrap an <img> inside an <a> tag to create a clickable image.

    <a href="https://example.com">
         <img src="logo.png" alt="Company Logo">
    </a>

    Using title for Tooltip

    The title attribute displays a tooltip when hovering over the image.

    <img src="icon.png" alt="Settings icon" title="Click for settings">