Episode 9 of 17

The img Tag

Learn how to add images to your web pages using the HTML img tag with proper attributes.

The img Tag

Images make web pages visually appealing. The <img> tag is how you embed images in HTML.

Basic Syntax

<img src="photo.jpg" alt="A beautiful sunset">

The <img> tag is a self-closing element — it has no closing tag.

Required Attributes

AttributePurposeRequired?
srcPath or URL to the image file✅ Yes
altAlternative text describing the image✅ Yes (for accessibility)

Optional Attributes

AttributePurpose
widthSets the image width (in pixels)
heightSets the image height (in pixels)
titleTooltip text shown on hover
loadingSet to "lazy" for lazy loading

Types of Image Paths

<!-- Same folder -->
<img src="photo.jpg" alt="Photo">

<!-- Subfolder -->
<img src="images/photo.jpg" alt="Photo">

<!-- Parent folder -->
<img src="../photo.jpg" alt="Photo">

<!-- External URL -->
<img src="https://example.com/photo.jpg" alt="Photo">

Why the alt Attribute Matters

  • Accessibility — screen readers read the alt text to visually impaired users
  • Broken images — alt text is shown if the image fails to load
  • SEO — search engines use alt text to understand what the image shows

Writing Good alt Text

✅ Good❌ Bad
alt="Golden retriever playing in a park"alt="dog"
alt="HTML code example in VS Code"alt="image1"
alt="" (for decorative images)alt="photo.jpg"

Supported Image Formats

  • JPEG (.jpg) — best for photographs
  • PNG (.png) — best for graphics with transparency
  • GIF (.gif) — for simple animations
  • SVG (.svg) — for scalable vector graphics (icons, logos)
  • WebP (.webp) — modern format with better compression

Key Takeaways

  • Use <img src="..." alt="..."> to add images
  • Always include an alt attribute for accessibility
  • src can be a relative path or an absolute URL
  • Use width and height to control image size
  • Choose the right image format for your use case