Build a Drupal custom formatter for caption overlays
An image with a caption overlay combines a picture and its explanation in one visual unit. That pattern suits Drupal sites built by Australian studios, community organisations and tourism businesses, where editors need consistent layouts without maintaining a custom template for every content type. It also gives mobile readers a compact way to understand a photograph while browsing on a phone during a Sydney train journey.
The solution is a small field formatter that renders the image, reads a sibling caption field and adds configurable positioning. An editor can place the caption in a corner, adjust its background opacity and reuse the same display across content types. Because the formatter handles presentation rather than data, the caption remains searchable and the image keeps its own alt text. The approach also leaves room for a future media-library workflow.
The examples below follow Drupal 10 conventions and target a standard Image field. They deliberately separate visible captions from accessibility metadata, check file access and use a responsive Twig template. Drupal 11 projects can retain the same formatter logic while moving plugin metadata to the attribute-based API.
Compare the implementation options
There are several ways to place a caption over an image in Drupal. The deciding factors are the content model, the number of editors and how much the display must change between sites.
| Approach | Best fit | Caption source | Main trade-off |
|---|---|---|---|
| Core Image display formatter | Simple image fields | Separate text field | No overlay controls |
| Twig field preprocessing | One site-specific layout | Sibling caption field | Couples display to the theme |
| Media entity resolution | Media library workflows | Media caption field | Requires resolving the source image |
| Custom field formatter | Reusable, configurable displays | Sibling or resolved media field | Requires a maintained module |
A custom formatter is the strongest option when the same behaviour must work across several content types. Twig preprocessing is quicker for a single template, while the standard Image display formatter cannot combine a caption with overlay controls. For a media library, the caption can live on the media entity; with a direct Image field, a sibling field keeps the relationship visible in the content form.
Configure the image and caption fields
Create an Image field named field_hero_image and a plain-text Long Text field named field_caption on the same content type. Make the caption optional where a photograph can stand alone, and constrain its length if short labels suit the design. Do not add the caption as another Image field property: core image data includes file information, dimensions, alt text and title, but a visible caption needs storage of its own. For the wider workflow, Drupalwoo module guidance is a useful companion.
Keep the caption field single-valued for this implementation and pair it with one image field. The formatter reads the first caption on the entity, so a multi-value gallery requires explicit mapping between each image delta and its matching caption. If your team already uses the Media library, store an entity reference to the image media type, add a caption field to that media bundle, and resolve the media’s source image before rendering.
Alt text and a caption serve different purposes. Alt text describes the image for people who cannot see it, while the caption adds context, a credit or an explanation for everyone. A caption may expand on the alt text, but repeating it verbatim creates unnecessary duplication for screen-reader users. If an overlay carries a price or promotional claim, the Australian Consumer Law still applies and the wording must not mislead.
Create the custom formatter plugin
Create an image_overlay module and add src/Plugin/Field/Formatter/ImageOverlayFormatter.php. The plugin annotation gives the formatter a stable ID, image_overlay, which Drupal uses when storing its display configuration. The class extends FormatterBase, declares two settings and returns a render array. That separation lets Twig control the markup and CSS control the overlay without embedding presentation rules in PHP.
Start with the module definition:
name: 'Image caption overlay'
type: module
description: 'Adds a configurable caption overlay to image fields.'
core_version_requirement: ^10
The formatter plugin contains the following implementation:
<?php
namespace Drupal\image_overlay\Plugin\Field\Formatter;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Field\FormatterInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
/**
* @FieldFormatter(
* id = "image_overlay",
* label = @Translation("Image with caption overlay"),
* class = "Drupal\\image_overlay\\Plugin\\Field\\Formatter\\ImageOverlayFormatter"
* )
*/
class ImageOverlayFormatter extends FormatterBase {
public function settingsForm(array $form, FormatterInterface $formatter) {
$form['overlay_position'] = [
'#type' => 'select',
'#title' => new TranslatableMarkup('Caption position'),
'#options' => [
'bottom-left' => new TranslatableMarkup('Bottom left'),
'bottom-right' => new TranslatableMarkup('Bottom right'),
'top-left' => new TranslatableMarkup('Top left'),
'top-right' => new TranslatableMarkup('Top right'),
],
'#default_value' => $formatter->getSetting('overlay_position') ?? 'bottom-left',
];
$form['background_opacity'] = [
'#type' => 'number',
'#min' => 0,
'#max' => 100,
'#title' => new TranslatableMarkup('Background opacity'),
'#default_value' => $formatter->getSetting('background_opacity') ?? 80,
];
return $form;
}
public function viewElements(FieldItemListInterface $items, $langcode) {
$entity = $items->getEntity();
$caption = '';
if ($entity && $entity->hasField('field_caption')) {
$caption_item = $entity->get('field_caption')->first();
if ($caption_item) {
$caption = trim(strip_tags((string) $caption_item->value));
}
}
$build = [];
foreach ($items as $delta => $item) {
$file = $item->entity;
if (!$file || !$file->access('view')) {
continue;
}
$build[$delta] = [
'#theme' => 'image_overlay',
'#file_url' => $file->url()->toString(),
'#alt' => (string) $item->alt,
'#width' => $item->width,
'#height' => $item->height,
'#caption' => $caption,
'#position' => $this->getSetting('overlay_position') ?? 'bottom-left',
'#opacity' => $this->getSetting('background_opacity') ?? 80,
];
$build['#cache']['tags'] = array_merge(
$build['#cache']['tags'] ?? [],
$file->getCacheTags()
);
}
$build['#attached']['library'][] = 'image_overlay/overlay';
$build['#cache']['contexts'][] = 'user.permissions';
return $build;
}
}
The formatter reads the caption from the containing entity, verifies that the referenced file is viewable and passes the URL, dimensions, alt text and caption to the theme layer. strip_tags() removes markup from the plain-text caption, and Twig escapes it again on output. For a media-reference field, resolve field_media_image to the underlying file and read the caption from the media entity first; a media entity is not itself an image file.
Render an accessible responsive overlay
Register a theme hook, a Twig template and a CSS library. The formatter attaches that library through #attached, so no custom JavaScript is required for the static overlay. The template uses a figure element and a figcaption, preserving the relationship between an illustration and its description in the accessibility tree.
Define the theme hook in image_overlay.module:
function image_overlay_theme($existing, $type, $theme, $path) {
return [
'image_overlay' => [
'variables' => [
'file_url' => '',
'alt' => '',
'width' => NULL,
'height' => NULL,
'caption' => '',
'position' => 'bottom-left',
'opacity' => 80,
],
],
];
}
Create templates/image_overlay.html.twig:
<figure class="image-overlay image-overlay--{{ position }}">
<img class="image-overlay__image"
src="{{ file_url }}"
alt="{{ alt }}"
width="{{ width }}"
height="{{ height }}">
{% if caption %}
<figcaption class="image-overlay__caption"
style="--image-overlay-opacity: {{ opacity / 100 }};">{{ caption }}</figcaption>
{% endif %}
</figure>
Add the styling to css/image-overlay.css:
.image-overlay {
position: relative;
display: inline-block;
max-width: 100%;
margin: 0;
}
.image-overlay__image {
display: block;
width: 100%;
height: auto;
}
.image-overlay__caption {
position: absolute;
box-sizing: border-box;
max-width: min(36rem, 90%);
margin: 0;
padding: .65rem .9rem;
background: rgb(0 0 0 / var(--image-overlay-opacity, .8));
color: #fff;
line-height: 1.4;
}
.image-overlay--bottom-left .image-overlay__caption { left: 0; bottom: 0; }
.image-overlay--bottom-right .image-overlay__caption { right: 0; bottom: 0; }
.image-overlay--top-left .image-overlay__caption { left: 0; top: 0; }
.image-overlay--top-right .image-overlay__caption { right: 0; top: 0; }
@media (max-width: 37.5rem) {
.image-overlay__caption {
position: static;
max-width: none;
}
}
Expose the stylesheet through image_overlay.libraries.yml:
image_overlay:
version: 1.x
css:
theme:
css/image-overlay.css: {}
The position classes let an editor choose a corner without changing markup, while the opacity variable controls the translucent black background. Test that white text remains readable over the brightest part of a photograph, because an 80 per cent background can still lose contrast against a white sky. Captions also need room: on a narrow screen the example moves the caption below the picture, where it cannot obscure an important subject or force an unreadable block over the image.
This version renders the original uploaded file to keep the example understandable. A production site should normally resolve an Image style derivative and return the derivative’s dimensions, especially for large photographs. Preserve intrinsic width and height to reduce layout shift, and lazy-load only images below the fold. A first hero image should remain eager for a fast Largest Contentful Paint on mobile connections.
Test, deploy and maintain the formatter
A reusable formatter needs both technical tests and an editorial handoff. Check it as a display option on every relevant content type, with and without captions, and confirm that file access, cache rebuilds and image-style settings behave as expected. These checks catch common failures before a release reaches editors.
Build and release checks
- Confirm the formatter appears in the image field’s Display options and saves each corner position and opacity value.
- Test a missing caption, a long caption, a replacement image and a file that an editor cannot view.
- Check keyboard navigation, zoom, screen-reader output and colour contrast against bright and dark photographs.
- Verify thumbnail generation, cache rebuilds, image dimensions and browser console errors.
Australian content governance also belongs in the release plan. Under the Privacy Act 1988, the Australian Privacy Principles may apply to personal information stored in a caption field. A public overlay can expose that information to search engines and cached pages, so assess the content type, audience and access controls before publication.
Editorial handover checks
- Record the required field names, supported Drupal versions and display defaults in the content guide.
- Give editors permission to change display settings without altering source data or templates.
- Confirm that the caption’s privacy classification matches where and how the image will be published.
The release record identifies the formatter version, supported Drupal versions and tested display settings. That reference lets support staff reproduce a problem quickly and keeps the overlay consistent across content types.