Embedding Images in HTML

1

Embedding Images in HTML

▶

Images are among the most powerful tools for communication on the web. They can convey emotion, illustrate concepts, guide users through interfaces, and make content far more engaging than text alone. Understanding how to embed images correctly in HTML is therefore a foundational skill — not just for getting pictures to appear on screen, but for doing so in a way that is accessible, performant, and semantically meaningful. This topic covers everything you need to know: the element itself, how to point it at the right file, how to describe it for users who cannot see it, how to control its dimensions, which file format to choose, and how to follow accessibility best practices throughout.

The element used to embed images in HTML is <img>. Unlike most HTML elements, it is a void element, meaning it has no closing tag and no content placed between tags. All the information the browser needs — where to find the image, how to describe it, how large to display it — is supplied entirely through attributes written inside the opening tag. A minimal, correct image element looks like this:

<img src="photos/sunset.jpg" alt="A warm orange and pink sunset over the ocean">

Because <img> is an inline element, it sits within the normal flow of text and other inline content. You place it exactly where you want the image to appear in the document, and the browser renders it at that position. It is one of the most frequently used elements in everyday HTML, appearing in everything from simple blog posts to complex web applications.

Setting the Source Path with src

The src (source) attribute is mandatory — without it, there is no image to display. Its value is a URL or file path that tells the browser where to retrieve the image file. There are two fundamental ways to write this path: as a relative path or as an absolute URL.

A relative path describes the location of the image file relative to the HTML document that contains the <img> tag. This approach is ideal for images that are part of your own project and hosted on the same server. For example, if your HTML file lives at mysite/index.html and your image lives at mysite/images/logo.png, you would write:

<img src="images/logo.png" alt="Company logo">

If the image were in the same folder as the HTML file, you would simply write the filename:

<img src="logo.png" alt="Company logo">

To navigate up a directory level, use ../. For instance, if your HTML file is inside a pages/ subfolder but the image is back in the root, you would write:

<img src="../images/logo.png" alt="Company logo">

An absolute URL provides the full web address of an image, including the protocol. Use this when linking to an image hosted on an external server:

<img src="https://www.example.com/images/banner.jpg" alt="A promotional banner">

Be aware that relying on images hosted on someone else's server (a practice called hotlinking) is generally discouraged — the other server's owner may remove the image, change its URL, or block external requests, all of which will break your page.

When the src path is wrong — due to a typo, a missing file, or a restructured directory — the browser cannot retrieve the image and displays a broken image icon in its place, often accompanied by the alt text. Keeping file paths accurate and consistent is therefore important for maintaining a working page.

Providing Alt Text for Accessibility

The alt attribute provides a text alternative for the image. It is not optional for informational images — omitting it entirely creates a poor experience for users who depend on assistive technologies and can even harm SEO. The value of alt should be a concise, accurate description of what the image means in context, not necessarily a literal catalogue of every visual detail.

Consider the difference between these two descriptions for a photo of a dog catching a frisbee in a park:

  • Poor alt text: alt="image" — tells the user nothing meaningful.
  • Acceptable alt text: alt="A brown Labrador catching a red frisbee" — describes appearance.
  • Better alt text (context-aware): alt="Max, our office dog, playing fetch during the team picnic" — describes purpose and meaning.

Screen readers — software used by people who are blind or have low vision — read the alt text aloud when they encounter an image. If the alt text is absent or unhelpful, those users miss the information the image was meant to convey. Here is a correctly written example:

<img src="team-photo.jpg" alt="The five-person development team standing together in front of the company headquarters">

Alt text also matters for search engine optimization (SEO). Search engine crawlers cannot "see" images the way humans do; they rely on alt text, filenames, and surrounding content to understand what an image depicts. Meaningful alt text therefore helps your images appear in image search results and contributes to the overall relevance signals for your page.

A practical guideline: write alt text by imagining you are describing the image to someone over the phone. Include only what is relevant to the purpose the image serves on that particular page.

Controlling Image Size with width and height

The width and height attributes specify the displayed dimensions of the image in pixels. Crucially, the values are plain integers — do not include the px unit or any other unit inside the HTML attribute:

<!-- Correct -->
<img src="banner.jpg" alt="A promotional banner" width="800" height="400">

<!-- Incorrect — do not include 'px' in HTML attributes -->
<img src="banner.jpg" alt="A promotional banner" width="800px" height="400px">

One important reason to always specify both width and height — even when you plan to resize the image with CSS — is layout stability. When the browser encounters an <img> element, it begins rendering the page without necessarily having received the image file yet. If the dimensions are not declared, the browser cannot reserve the right amount of space, and when the image finally loads, surrounding text and elements jump to accommodate it. This undesirable behaviour is measured by a web performance metric called Cumulative Layout Shift (CLS). By providing width and height, you allow the browser to calculate and hold the correct space from the very beginning.

If you need to override these values visually — for example, to make images fluid in a responsive layout — use CSS:

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

The HTML attributes still serve their layout-reservation purpose, while CSS controls how the image actually scales on different screens. The height: auto rule ensures the image maintains its original aspect ratio when the width changes.

Choosing the Right Image Format

Not all image formats are equal. Each format has strengths and weaknesses that make it more or less suitable for different kinds of visual content. Choosing the wrong format can result in unnecessarily large files, poor image quality, or missing features like transparency. The four formats you will most commonly encounter on the web are JPEG, PNG, WebP, and SVG.

Format Best For Compression Transparency Scalability
JPEG (.jpg / .jpeg) Photographs, complex scenes with gradients Lossy — small file size, slight quality loss No Pixel-based; quality degrades when enlarged
PNG (.png) Logos, icons, screenshots, images needing transparency Lossless — larger files but no quality loss Yes (alpha channel) Pixel-based; quality degrades when enlarged
WebP (.webp) Photos and graphics where small file size matters Lossy or lossless — typically 25–35% smaller than JPEG/PNG Yes Pixel-based; quality degrades when enlarged
SVG (.svg) Icons, logos, illustrations, diagrams Vector-based — file size depends on complexity Yes Perfect at any size — no quality loss

JPEG (Joint Photographic Experts Group) uses lossy compression, discarding some image data to achieve smaller file sizes. For photographs with millions of colours and smooth gradients — a landscape, a portrait, a product shot — this trade-off is almost invisible to the human eye at normal quality settings. JPEG does not support transparency, so it is unsuitable for logos that need to sit on top of differently coloured backgrounds.

PNG (Portable Network Graphics) uses lossless compression, preserving every pixel exactly. This makes it ideal for images with sharp edges, flat areas of colour, or text — scenarios where JPEG's compression artefacts would be distractingly visible. Its support for an alpha channel means pixels can be fully transparent, semi-transparent, or fully opaque, which is essential for overlaid graphics.

WebP is a modern format developed by Google that can operate in both lossy and lossless modes while achieving significantly smaller file sizes than JPEG or PNG at equivalent visual quality. It also supports transparency. Browser support is now excellent across all major current browsers, making WebP a strong default choice for new projects. The main consideration is that very old browsers (Internet Explorer, for instance) do not support it — if you must support those environments, provide a JPEG or PNG fallback using the <picture> element.

SVG (Scalable Vector Graphics) is fundamentally different from the others: it describes images using mathematical paths and shapes defined in XML rather than storing a grid of pixels. This means an SVG icon looks identically crisp on a small mobile screen and a 4K monitor, because it is redrawn at whatever size is needed. SVGs are perfect for logos, icons, charts, and illustrations. They can also be styled and animated with CSS and JavaScript. For photographs or highly detailed illustrations, however, SVG files can become extremely large and complex, so raster formats remain the better choice there.

Image Accessibility Best Practices

Writing a technically correct <img> element is only part of using images responsibly. Truly accessible image use requires thinking carefully about purpose, context, and the experience of every user — including those who cannot see the image at all.

The most important distinction is between informational images and decorative images. An informational image conveys meaning that is not provided elsewhere in the surrounding text — it adds something to the user's understanding. A decorative image is purely aesthetic; it enhances the visual design but conveys no unique information. These two categories are handled differently:

  • Informational images must have meaningful alt text that conveys the same information a sighted user would gain from seeing the image.
  • Decorative images should use an empty alt attribute — alt="" — so that screen readers skip over them entirely, avoiding unnecessary noise for the user.
<!-- Informational image: describe its meaning -->
<img src="error-icon.png" alt="Error: your form could not be submitted">

<!-- Decorative image: empty alt tells screen readers to ignore it -->
<img src="decorative-swirl.png" alt="">

Never omit the alt attribute entirely on a decorative image. When alt is absent, some screen readers will announce the image filename instead — which is far worse than silence.

Another critical practice is to avoid placing important text inside image files. Text that exists only as pixels — baked into a photograph or designed as a graphic — cannot be read by screen readers, cannot be selected or copied by users, cannot be translated by browser translation tools, and will appear blurry if the image is scaled up. If a heading, a call-to-action, or any other important message is part of your design, it should be real HTML text, potentially positioned over the image with CSS.

When displaying images with a visible caption — a labelled diagram, a photograph with a credit line, a chart with a title — the correct semantic approach is to use the <figure> and <figcaption> elements. This pair creates an explicit association between the image and its caption that both browsers and assistive technologies can understand:

<figure>
  <img src="annual-revenue-chart.png" alt="Bar chart showing annual revenue growth from 2020 to 2024">
  <figcaption>Figure 1: Annual revenue increased by 42% over the four-year period.</figcaption>
</figure>

When using <figure> and <figcaption>, the alt text and the caption serve different purposes. The alt text replaces the image for users who cannot see it; the caption supplements the image for all users. The alt text should therefore not simply duplicate the caption word for word.

Finally, consider colour contrast in images that convey meaning through colour — for example, a chart that uses red and green to distinguish data series. Users with colour blindness may not be able to tell those apart. Supplement colour with patterns, labels, or shapes so the information remains accessible regardless of how the colour is perceived. This principle applies not just to images you create, but to any images you choose to include in your content.

Bringing all of these practices together, here is a complete, well-formed image element that demonstrates best practices in a real-world context:

<figure>
  <img
    src="images/team-workshop.webp"
    alt="Eight team members collaborating around a whiteboard covered in sticky notes during a product planning workshop"
    width="960"
    height="640"
  >
  <figcaption>The product team during the Q3 planning workshop, July 2024.</figcaption>
</figure>

This single element chooses an efficient modern format (WebP), declares dimensions to prevent layout shift, provides meaningful alt text that conveys the scene's purpose, and wraps the whole thing in semantic markup that connects the image to its visible caption. Every decision reinforces the others, resulting in an image that is fast, accessible, and correctly integrated into the document.

NotesCovers the full lifecycle of embedding an image in HTML: the void element syntax, relative vs absolute src paths, meaningful alt text authoring, width/height attributes for layout stability, a comparison of JPEG/PNG/WebP/SVG formats, and the informational vs decorative image accessibility distinction including figure/figcaption usage.