October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
accessibility

How to Add Images in HTML Code: A Complete Guide to Paths, Alt Text, Responsive Images, and Performance

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To add an image in HTML, use the void <img> element with a source and alternative text:

<img src="images/photo.jpg" alt="A description of the photo">

The src value must resolve to an image URL or file that the browser can access. The alt value describes the image for people using screen readers and appears when the image cannot load. For production pages, also provide intrinsic width and height, choose responsive sources when needed, and load below-the-fold images lazily.

The basic HTML image syntax

An image is inserted with <img>. Unlike paragraph or heading elements, <img> is a void element: it does not wrap child content and has no closing tag.

<img src="images/photo.jpg" alt="A grapefruit slice on a plate">

src is the resource location. It can be a relative path such as images/photo.jpg, a root-relative path such as /images/photo.jpg, or an absolute HTTPS URL. The browser resolves a relative path from the page URL, not necessarily from your project folder. A spelling error, wrong capitalization, missing file, or server permission can produce a broken image.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Sale
HTML and CSS: Design and Build Websites
  • HTML CSS Design and Build Web Sites
  • Comes with secure packaging
  • It can be a gift option

Use meaningful alternative text

alt is replacement text. Describe the information the image contributes rather than listing visual details that do not matter. For example:

<img src="team.jpg" alt="The design team reviewing wireframes around a table">

If an image is purely decorative and conveys no information, use an empty value (alt="") so assistive technology can skip it. Do not omit the attribute: an omitted alt leaves its purpose unclear.

Reserve the correct space

Include the image’s intrinsic dimensions when known. HTML dimensions are unitless pixel values:

<img
  src="images/grapefruit-slice.jpg"
  alt="A grapefruit slice on a plate"
  width="800"
  height="600">

The browser can calculate the aspect ratio and reserve space before downloading the file, reducing layout shifts. These attributes do not force the image to remain 800 pixels wide; CSS can scale it.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Make images responsive with CSS

A common baseline rule keeps an image inside its containing block while preserving its proportions:

img {
  max-width: 100%;
  height: auto;
}

Use this with explicit HTML dimensions. The image shrinks on narrow screens and does not become wider than its container.

Serve different resolutions with srcset and sizes

If the same picture is available at several resolutions, give the browser candidates and describe the rendered slot:

<img
  src="photo-800.jpg"
  srcset="photo-480.jpg 480w, photo-800.jpg 800w, photo-1600.jpg 1600w"
  sizes="(max-width: 600px) 100vw, 800px"
  alt="A person standing beside a lake"
  width="800"
  height="600">

The w descriptors state each file’s intrinsic width. sizes tells the browser how wide the image will be in the layout, allowing it to select an appropriate candidate for the viewport and pixel density. Keep src as a fallback. Do not mix width descriptors (w) and density descriptors (x) in one srcset.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

When density descriptors are appropriate

For a fixed rendered size, you can describe alternatives by device pixel ratio:

<img
  src="logo.png"
  srcset="logo.png 1x, [email protected] 2x"
  alt="Acme logo"
  width="200"
  height="60">

Use either this density form or the width-and-sizes form for a given image, not both together.

Use <picture> for art direction and formats

Choose <picture> when a narrow screen needs a different crop, or when you want to offer alternate formats. Every <picture> must contain a fallback <img>; that image is displayed when no source matches or a format is unsupported.

<picture>
  <source srcset="portrait-crop.webp" media="(max-width: 600px)" type="image/webp">
  <source srcset="wide-image.webp" type="image/webp">
  <img
    src="wide-image.jpg"
    alt="A person standing beside a lake"
    width="1200"
    height="800">
</picture>

The browser evaluates <source> elements in order. The fallback <img> supplies the actual rendered element and its accessibility text.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Art direction versus resolution switching

  • Resolution switching: use one <img> with srcset and sizes when the composition stays the same.
  • Art direction: use <picture> when the crop or composition changes by media condition.
  • Format alternatives: use type on sources and retain a widely supported fallback in src.

Control when images load

Images load eagerly by default. For content well below the initial viewport, add loading="lazy":

<img
  src="gallery/photo.jpg"
  alt="A red bicycle leaning on a brick wall"
  width="1200"
  height="800"
  loading="lazy">

Keep width and height on lazy images. Before the resource arrives, an unloaded lazy image can otherwise have no reserved dimensions and cause reflow when it enters view. Do not lazy-load a hero image or another image that should appear immediately: deferring it can delay the first visual content.

Useful loading-related attributes

  • decoding="async" permits asynchronous image decoding where supported; it is an optional hint, not a replacement for correct dimensions.
  • fetchpriority="high" can identify an especially important above-the-fold image, but apply it sparingly.
  • Compression, correctly sized files, and modern formats usually matter more than adding attributes indiscriminately.

Relative paths, absolute URLs, and common project layouts

Image beside the HTML file

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

Image in a child directory

<img src="images/photo.jpg" alt="...">

HTML in a nested directory

If about/index.html needs a file at images/team.jpg in the site root, move up one level:

Rank #4
Sale
Web Design with HTML, CSS, JavaScript and jQuery Set
  • Brand: Wiley
  • Set of 2 Volumes
  • A handy two-book set that uniquely combines related technologies Highly visual format and accessible language makes these books highly effective learning tools Perfect for beginning web designers and front-end developers
<img src="../images/team.jpg" alt="...">

Absolute remote image

<img src="https://example.com/assets/photo.jpg" alt="...">

Remote hosts may block hotlinking, require authentication, change URLs, or serve an incompatible response. For reliable pages, host assets under your control and verify the request in your browser’s network panel.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A complete accessible, responsive example

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Image example</title>
  <style>
    img { max-width: 100%; height: auto; display: block; }
  </style>
</head>
<body>
  <main>
    <h1>Lake walk</h1>
    <picture>
      <source srcset="lake-narrow.webp" media="(max-width: 600px)" type="image/webp">
      <source srcset="lake-wide.webp" type="image/webp">
      <img
        src="lake-wide.jpg"
        srcset="lake-480.jpg 480w, lake-960.jpg 960w, lake-1440.jpg 1440w"
        sizes="(max-width: 600px) 100vw, 960px"
        alt="A person standing beside a lake at sunset"
        width="1440"
        height="960"
        loading="lazy"
        decoding="async">
    </picture>
  </main>
</body>
</html>

In a real page, ensure every file named in src or srcset exists at the deployed URL, and keep the fallback meaningful even if modern formats are unavailable.

Troubleshoot a missing or incorrect image

Broken-image icon or 404 response

  • Open the image URL directly in a browser.
  • Check spelling, capitalization, extension, and relative-path depth.
  • Inspect the Network panel for the exact requested URL and HTTP status.
  • Confirm the server returns an image content type and allows access.

The image appears stretched

Check that the HTML width and height reflect the file’s real aspect ratio. Use height: auto in CSS. If a fixed box is intentional, use object-fit: cover and accept cropping.

The wrong responsive file is selected

Verify that width descriptors are accurate, sizes matches the actual layout slot, and the browser is not using a cached response. Do not mix w and x descriptors.

The image is missing inside <picture>

Make sure the fallback <img> is present and that each <source> has valid syntax. A <source> element alone does not render an image.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Layout jumps while scrolling

Add accurate intrinsic dimensions to every image, including lazy-loaded images. If an image’s dimensions are unknown, determine them from the source asset or reserve space with a controlled aspect-ratio container.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Performance and reliability checklist

  • Resize files to the largest display size you actually need.
  • Compress images and offer suitable modern formats with a fallback.
  • Set width and height to reserve layout space.
  • Use srcset and sizes for same-crop images at multiple resolutions.
  • Use <picture> for art direction or format selection.
  • Lazy-load images below the fold, not the primary hero image.
  • Write concise, information-rich alt text; use empty alt for decoration.
  • Test at narrow and wide viewport widths and with images disabled.

Or skip the browser setup

If your goal is to obtain an image of a web page rather than embed an asset in your own HTML, ScreenshotNeo provides a screenshot API and MCP server. It accepts consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each step can be disabled. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing status. Its MCP tools—take_screenshot, get_page_info, and capture_pdf—work with Claude, Cursor, and other MCP clients.

One GET request returns PNG, JPEG, WebP, or PDF. See the ScreenshotNeo documentation for all options.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

Features include full-page and CSS-selector captures, dark mode, device presets, arbitrary viewports, retina scale, PDF paper and page controls, custom CSS and JavaScript, clicks, waits, request blocking, headers, cookies, user agents, authorization, timezone, geolocation, transparent backgrounds, resizing, configurable cache TTL, signed image links, asynchronous webhooks, bulk capture of up to 100 URLs per call, usage data, and an OpenAPI specification. Existing parameter names used by other screenshot APIs also work.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The Free plan includes 1,000 screenshots each month without a card. Paid plans start at $5 for 3,000 shots; yearly billing provides two months free, and every feature is included on every plan. Create a free ScreenshotNeo account.

Frequently Asked Questions

Should I put an image in a paragraph element?

No. Place <img> where it belongs in the document flow; wrap it in <figure> when you also need a caption.

Can CSS replace the HTML alt attribute?

No. CSS background images do not provide equivalent replacement text. Use an HTML image when the visual conveys content.

What happens if JavaScript is disabled?

A normal <img>, including the fallback inside <picture>, still loads without JavaScript.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Read next

Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.