Images
Visual elements like images, illustrations, and diagrams play a crucial role in web content. HTML provides the <img>
element to embed images directly into your web pages.
Embedding Images (<img>
)
The <img>
element is used to embed an image file into an HTML document.
- It is an empty element, meaning it has no closing tag (
</img>
is incorrect). - It requires attributes to specify the image source and provide descriptive text.
- By default,
<img>
is an inline element. It flows along with text content, but its display behavior can be easily modified using CSS (e.g., making it block-level or using floats/flexbox/grid for layout).
Basic Syntax:
<img src="path/to/your/image.jpg" alt="Descriptive text about the image">
Image Attributes
Several attributes are essential or highly recommended when using the <img>
tag:
src
(Source):- Purpose: This required attribute specifies the path or URL to the image file you want to display. It works similarly to the
href
attribute for links:- Relative URL:
src="images/logo.png"
(for images within your site) - Absolute URL:
src="https://cdn.example.com/images/header.jpg"
(for images hosted externally)
- Relative URL:
- Requirement: Mandatory. The image will not display without a valid
src
.
- Purpose: This required attribute specifies the path or URL to the image file you want to display. It works similarly to the
alt
(Alternative Text):- Purpose: This required attribute provides a textual description of the image. It's crucial for:
- Accessibility: Screen readers read the
alt
text aloud for visually impaired users. - Fallback Content: The text is displayed if the image fails to load (e.g., incorrect path, slow network, user has images disabled).
- SEO: Search engines use
alt
text to understand the image content and context.
- Accessibility: Screen readers read the
- Requirement: Mandatory for meaningful images. Write concise yet descriptive text explaining the content and function of the image.
- Decorative Images: If an image is purely decorative and provides no informational value (e.g., a background pattern, a stylistic border), use an empty
alt
attribute (alt=""
) so screen readers can skip it. Do not omit thealt
attribute entirely. - Examples:
- Good:
alt="StepByStack logo featuring overlapping colored squares"
- Okay:
alt="Company logo"
- Bad:
alt="image"
oralt="logo.png"
- Decorative:
alt=""
(for a purely cosmetic divider image)
- Good:
- Purpose: This required attribute provides a textual description of the image. It's crucial for:
width
andheight
:- Purpose: Specify the dimensions (in pixels) that the image should occupy on the page.
- Benefits: Setting these attributes allows the browser to reserve the correct amount of space for the image before it fully loads. This prevents the page content from jumping around as images load (improving user experience and reducing Cumulative Layout Shift - CLS).
- Recommendation: Always include
width
andheight
attributes matching the image's intrinsic (actual) dimensions. While CSS can override these for responsive designs, providing them in HTML ensures space reservation during initial load. - Example:
<img src="photo.jpg" alt="Man coding on laptop" width="800" height="600">
title
:- Purpose: Provides additional, non-essential information about the image. Browsers usually display this as a tooltip on hover.
- Note:
title
is not a substitute foralt
text.alt
describes the image content/function, whiletitle
might offer supplementary info. It's often unnecessary if thealt
text is good.
Complete Example:
<img
src="images/tutorial-screenshot.png"
alt="Screenshot showing CSS code for styling a button"
width="750"
height="420"
title="CSS Button Styling Example"
>
Common Image Formats and Use Cases
Choosing the right image format affects file size, quality, and features like transparency or animation. Here are the most common web formats:
- JPEG (or JPG) (
.jpg
,.jpeg
):- Best for: Photographs, complex images with gradients and many colors.
- Pros: Excellent compression for photos (small file sizes). Widely supported.
- Cons: Lossy compression (quality degrades slightly with higher compression). Does not support transparency.
- PNG (Portable Network Graphics) (
.png
):- Best for: Logos, icons, illustrations, text-heavy graphics, images requiring transparency.
- Pros: Lossless compression (no quality loss). Supports alpha transparency (varying degrees of opacity). Good for sharp lines and solid colors.
- Cons: File sizes can be larger than JPEGs for photographic content.
- GIF (Graphics Interchange Format) (
.gif
):- Best for: Simple animations.
- Pros: Supports animation. Lossless compression (for its limited palette). Supports basic (non-alpha) transparency.
- Cons: Limited to 256 colors (poor for photos). Usually larger file sizes than modern video formats for animation. Mostly superseded by PNG for static images.
- SVG (Scalable Vector Graphics) (
.svg
):- Best for: Logos, icons, illustrations, charts, anything that needs to scale without quality loss.
- Pros: Vector-based (defined by math, not pixels). Infinitely scalable (looks sharp at any size). Often small file sizes for simpler graphics. Can be styled with CSS and manipulated with JavaScript. Text content is searchable and selectable.
- Cons: Not suitable for complex photographic images. Can become complex and large for highly detailed vector art.
- WebP (
.webp
):- Best for: A modern replacement for JPEG, PNG, and GIF, offering better compression.
- Pros: Provides superior lossy and lossless compression (smaller files at similar quality). Supports transparency and animation. Widely supported by modern browsers.
- Cons: Might require fallbacks (using the
<picture>
element) for compatibility with very old browsers.
General Guidance
Use JPEG for photos, PNG for graphics needing transparency, SVG for logos/icons, and consider WebP for optimized versions of JPEGs and PNGs.
Using Figures and Captions (<figure>
, <figcaption>
)
When an image (or illustration, diagram, code snippet, etc.) is self-contained content that's referenced from the main text, it's semantically appropriate to wrap it in a <figure>
element. You can then provide a caption using <figcaption>
.
<figure>
: Represents self-contained content, potentially with a caption. It can be moved away from the main flow (e.g., to an appendix) without affecting the document's meaning.<figcaption>
: Provides a caption or legend for the content of its parent<figure>
element. It should be the first or last child inside the<figure>
.
This structure explicitly associates the caption with the image, which is beneficial for accessibility and understanding the document structure.
<figure>
<img
src="images/html-structure.png"
alt="Diagram showing basic HTML page structure with head and body"
width="600"
height="400"
>
<figcaption>Fig. 1: The basic structural elements of an HTML document.</figcaption>
</figure>
<p>As shown in Fig. 1, every HTML page has a head and a body...</p>