Src and alt in HTML


In HTML, the src (short for "source") and alt (short for "alternative text") attributes are commonly used in conjunction with media elements like images and iframes. 

src Attribute

The src attribute specifies the path to the file you want to include in your HTML document, such as an image, video, or iframe.

src with an Image

<img src="path/to/image.jpg" alt="Description of the image">
  • src="path/to/image.jpg": The src attribute points to the location of the image file. This can be a relative path (as shown) or an absolute URL.
  • alt="Description of the image": The alt attribute provides alternative text for the image. This text is displayed if the image cannot be loaded and is also used by screen readers for accessibility.


src with an Iframe

<iframe src="https://www.example.com" title="Example Site"></iframe>
  • src="https://www.example.com": The src attribute here points to the URL of the webpage to be embedded within the iframe.
  • title="Example Site": This attribute gives a brief description of the iframe content, which helps with accessibility.


alt Attribute

The alt attribute is used with the <img> tag to provide a text alternative for an image. This is important for accessibility and for situations where the image cannot be displayed.

Alt with an Image

<img src="path/to/logo.png" alt="Company Logo">
  • src="path/to/logo.png": Specifies the path to the image file.
  • alt="Company Logo": Provides a text description of the image. This helps visually impaired users understand the content and also helps search engines understand the context of the image.


Combining src and alt in Practice

Let's say you have a website for a bakery and you want to include images of your products.

<h2>Our Products</h2>
<img src="images/cake.jpg" alt="Chocolate cake with frosting">
<img src="images/cookies.jpg" alt="Assorted cookies on a plate">
<img src="images/bread.jpg" alt="Freshly baked bread">
  • Each image has a src attribute pointing to the file location and an alt attribute describing the image content.
  • This ensures that users and search engines can understand the context of each image, even if the image fails to load.

Summary

  • src Attribute: Specifies the file path or URL for the media to be displayed.
  • alt Attribute: Provides alternative text for the image, aiding in accessibility and SEO.

Using these attributes correctly helps improve the usability and accessibility of your website.