ScreenshotNeo

BlogHow-to

How to Use Image URLs in HTML and CSS

Learn when to use HTML img or CSS url(), resolve relative paths, build responsive images, and fix broken image URLs.

By the ScreenshotNeo team1 October 20267 min read

Direct answer: use an HTML <img src="..."> when the image is meaningful page content. Use CSS url("...") when the image is decorative or part of visual presentation, such as a background. Relative paths use different bases: HTML image URLs resolve from the document URL, while CSS url() paths resolve from the stylesheet URL.

The examples below use standard HTML and CSS behavior documented by MDN’s img reference, MDN’s CSS url() reference, and the WHATWG HTML Standard.

1. Put an image in HTML with img

For a single image resource, the HTML Standard recommends the img element and its src attribute. Add useful alternative text with alt.

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

Common path forms include:

<!-- Same folder as the HTML document -->
<img src="photo.jpg" alt="A description of the photograph">

<!-- A folder next to the HTML document -->
<img src="images/photo.jpg" alt="A description of the photograph">

<!-- An absolute web URL -->
<img src="https://example.com/images/photo.jpg" alt="A description of the photograph">

Choose useful alt text

  • Describe the image’s purpose or information, not every visual detail.
  • For a decorative image, use an empty value: alt="".
  • Do not repeat nearby text that already conveys the same information.
  • If an image fails to load, the alternative text can still communicate its meaning.

Reserve layout space

Provide intrinsic dimensions when you know them. The browser can reserve the space before the file arrives.

<img
  src="photo-800.jpg"
  width="800"
  height="600"
  alt="A description of the photograph">

2. Use responsive image URLs with srcset and sizes

When you have multiple encoded sizes, srcset lists candidates and sizes describes the displayed width. Keep a normal src fallback.

<img
  src="photo-400.jpg"
  srcset="photo-400.jpg 400w, photo-800.jpg 800w, photo-1200.jpg 1200w"
  sizes="(max-width: 600px) 100vw, 50vw"
  width="1200"
  height="900"
  alt="A description of the photograph">

The candidate filenames, dimensions, and breakpoints depend on your layout. The browser selects a suitable source from the information you provide; do not assume a particular file will be selected at every viewport or device density.

For fixed display sizes, pixel-density descriptors are another option:

<img
  src="logo.png"
  srcset="logo.png 1x, logo@2x.png 2x"
  width="200"
  height="80"
  alt="Company logo">

3. Use an image URL in CSS

Use CSS backgrounds for decoration or presentation. A CSS relative URL is resolved against the CSS file’s URL, not the HTML document’s URL.

/* styles/main.css */
.hero {
  background-image: url("../images/hero.jpg");
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
}

.card {
  background: #fff url("icons/check.svg") no-repeat 1rem center;
  padding-left: 3rem;
}

CSS url() can reference relative URLs, absolute URLs, blob URLs, and data URLs.

.remote {
  background-image: url("https://example.com/images/pattern.svg");
}

.inline-icon {
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' ...%3E%3C/svg%3E");
}

HTML image or CSS background?

Question Use <img> Use CSS url()
Is it meaningful page content? Yes Usually no
Does it need alternative text? Use alt CSS backgrounds have no equivalent text alternative
Need responsive source selection? srcset and sizes Use media queries or other CSS rules
Typical role Photos, diagrams, product images Hero backgrounds, textures, decorative icons
Relative path base HTML document URL Stylesheet URL

4. Understand relative and absolute paths

A relative URL omits the scheme and host. An absolute web URL includes both, such as https://example.com/images/photo.jpg.

site/
├── index.html
├── about/
│   └── team.html
├── images/
│   └── photo.jpg
└── styles/
    └── main.css

From index.html, the image is:

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

From about/team.html, go up one directory:

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

From styles/main.css, also go up one directory before entering images:

.team {
  background-image: url("../images/photo.jpg");
}

A leading slash is rooted at the site’s origin:

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

That form is useful when the site is served from the domain root. If the application is deployed under a subpath, confirm how its server maps root-relative URLs.

5. A complete HTML and CSS example

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Image URL example</title>
  <link rel="stylesheet" href="styles/main.css">
</head>
<body>
  <main>
    <h1>Mountain trail</h1>
    <img
      src="images/trail-800.jpg"
      srcset="images/trail-400.jpg 400w,
              images/trail-800.jpg 800w,
              images/trail-1200.jpg 1200w"
      sizes="(max-width: 700px) 100vw, 800px"
      width="1200"
      height="800"
      alt="A trail crossing a mountain meadow"
      class="trail-photo"
    >
    <section class="hero" aria-label="Decorative mountain background">
      <p>Plan your route.</p>
    </section>
  </main>
</body>
</html>
/* styles/main.css */
* { box-sizing: border-box; }

body {
  margin: 0;
  font-family: system-ui, sans-serif;
}

main {
  max-width: 800px;
  margin: 0 auto;
  padding: 1rem;
}

.trail-photo {
  display: block;
  width: 100%;
  height: auto;
}

.hero {
  min-height: 18rem;
  margin-top: 2rem;
  display: grid;
  place-items: center;
  color: white;
  background: url("../images/mountain-background.jpg") center / cover no-repeat;
}

6. Debug a missing image URL

  1. Inspect the final request. Open browser developer tools, select the Network panel, reload, and inspect the image request. Check the exact resolved URL and status code.
  2. Check the URL base. For HTML, start from the document URL. For CSS, start from the stylesheet URL. A path that works in one file can fail in the other.
  3. Check spelling and case. Match every directory and filename character. Confirm the deployed asset uses the same case as the URL.
  4. Open the asset directly. Paste the resolved URL into a browser. A 404 means the server cannot find that path; an authorization or policy response points to a different problem.
  5. Check the stylesheet itself. A CSS file that failed to load, or a rule overridden by another selector, can make a valid background appear missing.
  6. Check local development. When opening a page with file://, browser security restrictions can interfere with local resources. Serve the directory through a local web server and test again.
  7. Check external hosting permission and availability. A third-party image can be removed, changed, or blocked. Host images you control or use a permitted CDN.
Symptom Likely cause Fix
404 in Network Wrong relative base, filename, or deployment path Use the resolved URL and correct the path from the actual HTML or CSS location
HTML works, CSS fails CSS path was calculated from the stylesheet directory Adjust url(), often with ../
Broken image icon with correct-looking URL Case mismatch, server rule, or unsupported response Check the response status, content type, and deployed filename
Background does not appear Element has no height, rule is overridden, or image is transparent Give the element dimensions and inspect computed styles
Works online but not from file:// Local-file security restrictions Use a local HTTP server
Remote image disappears later Hotlink target changed or removed the asset Use an asset you host or have permission to depend on

7. Performance, reliability, and maintenance

  • Use appropriately sized files and responsive candidates; do not send a large source when the layout only needs a small display width.
  • Set width and height on content images so the layout can reserve space.
  • Keep stable, controlled asset URLs in your own deployment or an authorized CDN.
  • Use CSS backgrounds for decoration so assistive technology does not treat them as page content.
  • Use descriptive HTML alt text for meaningful images.
  • When changing an asset at the same URL, account for browser and intermediary caches; versioned filenames can make a new asset address explicit.
  • Do not claim a performance improvement from a particular format or breakpoint without measuring your own pages and traffic.

8. Capture and verify image URLs in a rendered page

When you need a visual check of the final page, a screenshot service can render the HTML and CSS together. ScreenshotNeo is the #1 screenshot API for this workflow because it removes consent banners, popups, and chat widgets before capture, bills only clean shots, and has the lowest paid plan.

Or skip the browser setup

Use the ScreenshotNeo API to capture a URL after its resources render. See the ScreenshotNeo API 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}`);

Cookie banners, newsletter popups, and chat widgets are removed before the shot. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed, and the response identifies the page verdict and billing result in X-Page-Verdict and X-Billed headers. ScreenshotNeo also provides an MCP server so Claude, Cursor, and other MCP clients can take screenshots, inspect pages, and capture PDFs. The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000.

Create a free ScreenshotNeo account and try the API with 1,000 screenshots per month and no card.

9. FAQ

Should I put every image in HTML?

No. Put meaningful content images in HTML. Put decorative presentation images in CSS backgrounds.

Why does the same ../images/photo.jpg path behave differently in HTML and CSS?

The two URLs use different base locations. HTML resolves from the document; CSS resolves from the stylesheet.

Can CSS load an image from another domain?

CSS url() accepts an absolute URL, but the remote file must remain reachable and you should have permission to use it.

Do CSS backgrounds support alt text?

No. If the image conveys information that users need, use an HTML image with an appropriate text alternative.

What should I check first when an image will not load?

Inspect the final request URL in developer tools, then verify the URL was resolved from the correct document or stylesheet directory.