References

Beginner-friendly references for web development, with live, editable examples.

The HTML src attribute

Attribute All modern browsers Updated
Quick answer

The HTML src attribute specifies the URL of the resource to embed. It is used on the <img>, <script>, <iframe>, <audio>, <video>, <source>, <embed> and <track> elements.

Overview

The src attribute specifies the URL of an external resource to load and embed. What it points at depends on the element: the image file for an <img>, the JavaScript file for a <script>, the page for an <iframe>, and the media file for <audio>, <video> and <source>. On those elements it is essential — without it, there is nothing to load.

The path resolves relative to the document's URL (unlike the CSS url() function, which resolves relative to the stylesheet). Use a root-relative path like /images/photo.jpg or a full URL when you need to be explicit. For responsive images, pair src with srcset and sizes so the browser can choose the best file; src then acts as the fallback.

A few performance and reliability notes: set width and height (or a CSS aspect-ratio) on images and iframes so the layout does not shift while they load; add loading="lazy" to off-screen images and frames; and handle the error event to show a fallback when a resource fails to load.

Syntax

<img src="photo.jpg" alt="A description">

Values

Value
A URL pointing to the resource.

Example

Live example
<img src="https://codeshack.io/web/img/icon.png" alt="CodeShack logo" width="64" height="64">

Best practices

  • Always provide a src — the element loads nothing without it.
  • For images, pair it with srcset and sizes for responsive loading, with src as the fallback.
  • Set width and height so images and iframes do not cause layout shift.
  • Handle the error event to recover gracefully when a resource fails to load.

Frequently asked questions

What does the src attribute do?
It specifies the URL of an external resource to embed — an image, script, page or media file, depending on the element.
Is the src path relative to the HTML or the CSS?
To the HTML document's URL. (CSS url() paths, by contrast, resolve relative to the stylesheet.)
What is the difference between src and srcset?
src is a single URL (and the fallback); srcset lists multiple candidates from which the browser picks the best for the screen.
Which elements use the src attribute?