Image Attributes in HTML

Adding images to a webpage can make it more engaging and visually appealing. In HTML, the <img> tag is used to embed images. Let's explore some of the key attributes that enhance the functionality and accessibility of images.

1. src (Source)

This attribute specifies the path to the image file. It can be a URL or a relative path. html Copy code

HTMLcopy
<img src="images/example.jpg" alt="A beautiful sunset">

2. alt (Alternative Text)

The <alt> attribute provides a text description of the image. This is essential for screen readers and is displayed if the image fails to load. html Copy code

HTMLcopy
<img src="images/example.jpg" alt="A beautiful sunset">

Why it matters: It improves accessibility and enhances SEO.

3. width and height

These attributes set the dimensions of the image (in pixels).

HTMLcopy
<img src="images/example.jpg" alt="A beautiful sunset" width="300" height="200">

Tip: Avoid hardcoding dimensions; use CSS for better responsiveness.

4. title

The <title> attribute adds a tooltip that appears when you hover over the image. html Copy code

HTMLcopy
<img src="images/example.jpg" alt="A beautiful sunset" title="This is a sunset">

5. loading

The loading <loading> attribute improves page performance by controlling how images are loaded.

  • Lazy: Loads the image only when it appears in the viewport.
  • eager: Loads the image immediately.
HTMLcopy
<img src="images/example.jpg" alt="A beautiful sunset" loading="lazy">

6. crossorigin

This attribute specifies how the browser should handle cross-origin requests for the image. Common values:

  • anonymous: Sends no credentials.
  • use-credentials: Sends credentials like cookies.
HTMLcopy
<img src="https://example.com/image.jpg" alt="Cross-origin image" crossorigin="anonymous">



With these attributes, you can enhance both the user experience and the technical performance of your website

Page 20 of 33

Page 20 of 33

logoFALYTOM

Learn technologies like HTML, CSS, JavaScript, React, NodeJS and so much more. Practice your skills with our free games, examples, practice questions & quizzes

    © 2024 Tomilola Group
    • facebook logo
    • twitter logo
    • instagram logo
    • linkedin logo
    • github logo
    • youtube logo