Skip to main content
Recipe number 9

Cookbook · Chapter 7 · Figures & images

Figures that float to where you cite them

A two-column chapter with seven numbered figures: six float from their first :ref to the first slot their placement allows; one sits where ::resource puts it.

On this page

pp. 28–29 · 2–3 of 4

  • Trim 200 × 250 mm
  • 2 columns, 6 mm gutter
  • Faustina 9.4/13.4
  • IBM Plex Sans Condensed
  • Montserrat
  • 4 pages
  • Level
  • Postext 1.65.0
  • Laid out in 197 ms
  • 224 lines of code

In short

A chapter of a textbook about mountains, in two columns with seven numbered pictures. It shows how each picture moves to the first free space after the text first mentions it.

What you'll build

Chapter 2 of Mountain Landforms, a geomorphology textbook on a 200 × 250 mm page. A blue ribbon with the chapter number hangs from the head of the opener, beside the title's ice-blue slab; two justified columns of Faustina follow. The seven figures, paintings generated with diffusion models and labelled in code, are numbered in order of first mention. Six float to the first free slot their placement allows, counting from the paragraph that first cites them. Figure 2.1, auto, lands at the foot of the opener; 2.3 opens the right-hand column of page 28 and 2.2 fills the foot of that page; 2.4 and 2.5 open the two columns of page 29. Figure 2.6 is set where the text embeds it. Figure 2.7, a top float cited on page 30, would wait for page 31, but a float cannot leave its chapter, so it goes to the foot of page 30.

This recipe answers

  • How do I add a figure with a numbered caption and cite it in the text ("see Fig. 3.2")?
  • How do I control where a figure goes: top of page, across both columns, exactly here, or in the margin?
  • How do I get "Figure" and "Table" labels in my document's language?
  • How do I add images and tables from code (resources) instead of Markdown ![]()?

The short answer

script.js · lines 252–285in full code
// In the Markdown, :ref{id="valleys" case="lower"} prints 'fig. 2.1' and places Figure 2.1.
// Captions, credits and alt texts come from content.figures.<lang>.md.
const figure = (id, height, placement) => {
  if (!TEXTS[id]) throw new Error(`content.figures has no caption block for "${id}"`);
  const [caption, note, altText] = TEXTS[id];
  // An SVG fills the width of its slot (a column or the text block, or a fraction of
  // either), so its width and height only give its shape.
  const width = (placement.span === 'page' ? MEASURE : COLUMN) * (placement.width ?? 1);
  return { id, typeId: 'figure', kind: 'svg', caption, note, altText,
    svg: { fileId: `${id}.svg`, width, height }, placement, createdAt: 0, updatedAt: 0 };
};
// In any order: the first mention of each one in the text, a :ref or a ::resource line,
// decides its number.
const resources = [
  // Cited on the opener page: 'auto' may take that page's foot band, where 'top'
  // could only open the next page (gotcha: top-float-next-page).
  figure('valleys', 56, { position: 'auto', span: 'page' }),
  // Across both columns, but only in a foot band: the page it is cited on, if both
  // columns still have room there, else the foot of the next page.
  figure('profile', 60, { position: 'bottom', span: 'page' }),
  // A column figure that takes only a column head: the next one still empty after its
  // citation, here the right column of the same page, above the text that follows it.
  figure('cirque', 48, { position: 'top' }),
  // Cited in the same sentence, the two take the next two column heads, side by side.
  figure('abrasion', 48, { position: 'top' }),
  figure('plucking', 48, { position: 'top' }),
  // No float: set exactly where ::resource{id="roche"} stands, with the same gap above it
  // and below it.
  figure('roche', 42, { position: 'here' }),
  // A band of its own, half the text width and centred. It is cited on the chapter's last
  // page, where a 'top' float would wait for the next page; a float cannot leave its
  // chapter, so this one goes to the foot of the last page.
  figure('moraines', 50, { position: 'top', span: 'page', width: 0.5, align: 'center' }),
];

Six figures float to the first slot their placement allows; one stays put

Ingredients

Type
Faustina, Montserrat, IBM Plex Sans Condensed (SIL OFL 1.1)
Assets
  • abrasion-1080.jpg
  • cirque-1080.jpg
  • moraines-1080.jpg
  • plucking-1080.jpg
  • profile-1400.jpg
  • roche-1080.jpg
  • valleys-1536.jpg
  • Figure 2.1: a V-shaped river valley and a U-shaped glacial valley (Generated With Diffusion Models, original)
  • Figure 2.2: long profile of a valley glacier (Generated With Diffusion Models, original)
  • Figure 2.3: a glacial cirque in section (Generated With Diffusion Models, original)
  • Figure 2.4: abrasion at the base of the ice (Generated With Diffusion Models, original)
  • Figure 2.5: plucking on a rock step (Generated With Diffusion Models, original)
  • Figure 2.6: a roche moutonnée (Generated With Diffusion Models, original)
  • Figure 2.7: lateral, medial and terminal moraines in plan (Generated With Diffusion Models, original)

Method

#1 · One palette for the pages and the figures

script.js · lines 19–36in full code
const palette = {
  ink: '#1b2227', // text: a cold near-black
  glacier: '#34729a', // the accent: kicker, ribbon, caption labels, references, folios, water
  ice: '#e3f1f8', // the opener slab
  rock: '#5b5a57', // bedrock in the drawings
  moss: '#7d8f4e', // valley floors and pines
  rule: '#c6d3db', // the hairline under the running heads
  muted: '#5d6a72', // running heads, credit notes, the colophon
  paper: '#ffffff',
};
// A linked colour carries its hex and the palette entry it follows.
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
const colorPalette = [
  ...Object.entries(palette).map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } })),
  // The engine's defaults link to 'main-color' (#295aa3): pointing it at the accent keeps
  // that second blue off the page.
  { id: 'main-color', name: 'glacier (defaults)', value: { hex: palette.glacier, model: 'hex' } },
];

Every colour in the configuration links to one of these entries, and the paintings were generated in the same slate, glacier blue and moss, so the figures sit in the page's colours. A painting keeps its own colours: a new value for glacier changes the ribbon, the slab and the labels, not the ice in the figures. The accent is dark enough for small type: 5.2:1 on white for caption labels and citations, 4.5:1 on the ice slab for the kicker. Each figure is an SVG that embeds its painting as a JPEG data URL and sets its labels over it as text, with a thin white halo, so they stay sharp and follow the edition's language. The labels name IBM Plex Sans Condensed on the SVG, and the kit's loadSvg embeds the two weights they set through the engine's inlineSvgFonts, because an SVG shown as an image cannot reach the page's fonts by itself.

#2 · Name the figures in the reader's language

script.js · lines 47–56in full code
const captions = () => ({
  // The built-in types take their names from the locale: 'Figure 2.3' and 'fig. 2.3' with
  // 'en-us', 'Figura 2.3' with 'es', numbered {h1}.{n} per chapter. It sets hyphenation too.
  locale: t({ en: 'en-us', es: 'es' }),
  captionStyle: { // the text colour follows bodyText; the note is 0.85 × the caption size
    fontFamily: LABEL, fontSize: pt(8.3), gap: mm(2.2),
    labelColor: col('glacier'), descriptionItalic: true, // the label is bold by default
    note: { color: col('muted'), gap: mm(0.6) }, // the credit line
  },
});

locale names the built-in types in the document's language: captions read Figure 2.3 here and Figura 2.3 in the Spanish edition, where the same 'es' picks the Spanish hyphenation patterns. Each citation then takes the form its sentence needs: case="lower" for (fig. 2.1) and, with style="full", for (figure 2.2); style="number" after a plural (figures 2.4 and 2.5); and text="…" for a phrase such as the chapter’s first figure, which prints no number. That phrase points back to a figure already placed; as a first mention it would still number and place it.

#3 · A ribbon and a slab of ice for the opener

script.js · lines 60–110in full code
const at = (to, edge, x, y, width, height) => ({ anchor: { to, edge },
  offset: { x: mm(x), y: mm(y) },
  ...(width && { size: { width: mm(width), height: height ? mm(height) : 'auto' } }) });
const text = (id, content, family, size, color, placement, extra) => ({ kind: 'text', id,
  content, fontFamily: family, fontSize: pt(size), color: col(color), placement,
  align: 'left', ...extra });
const caps = (size) => ({ fontWeight: 600, textTransform: 'uppercase',
  letterSpacing: pt(size * 0.18) }); // capitals tracked 0.18 em
const [SLAB, RIBBON, RIBBON_END] = [64, 30, 70]; // mm: slab height; ribbon width and length
const [TEXT_X, KICKER_Y] = [RIBBON + 8, 10]; // mm: the opener texts start 8 mm right of the ribbon
const [TITLE_W, LEAD_W] = [118, 112]; // mm: the title's measure, and a shorter standfirst
const opener = {
  enabled: true,
  // At least 5 mm under the slab; the reserve then rounds up to whole 13.4 pt grid lines,
  // so here 69 mm becomes 15 lines (70.9 mm) and the text starts about 7 mm under the slab.
  minHeight: mm(SLAB + 5),
  slot: { elements: [
    { kind: 'box', id: 'slab', style: { backgroundColor: col('ice') }, // runs off the fore-edge
      placement: at('container', 'top-left', 0, 0, MEASURE + OUTER, SLAB) },
    { kind: 'box', id: 'ribbon', style: { backgroundColor: col('glacier') }, // hangs from the head
      placement: at('page', 'top-left', INNER, 0, RIBBON, RIBBON_END) },
    text('numeral', '{chapterNumber}', DISPLAY, 80, 'paper', // an 80 pt line box is 28 mm tall:
      at('page', 'top-left', INNER, RIBBON_END - 31, RIBBON), // it ends 3 mm above the foot
      { fontWeight: 800, lineHeight: 1, align: 'center' }),
    text('kicker', t({ en: 'Chapter {chapterNumber} · {attr.topic}',
      es: 'Capítulo {chapterNumber} · {attr.topic}' }), LABEL, 8.5, 'glacier',
    at('container', 'top-left', TEXT_X, KICKER_Y), caps(8.5)),
    text('title', '{titleText}', DISPLAY, 27, 'ink', at('#kicker', 'below', 0, 2.6, TITLE_W),
      { fontWeight: 800, lineHeight: 1.06 }),
    text('lead', '{attr.lead}', TEXT, 10.6, 'ink', at('#title', 'below', 0, 4.2, LEAD_W),
      { italic: true, lineHeight: 1.38, hyphenate: true }),
  ] },
};
const HAIRLINE = TOP - 5; // mm from the top edge: the rule under the running heads
const HEAD_Y = HAIRLINE - 4.4; // the running heads' line box, 4.4 mm above the hairline
const head = (id, content, parity, edge, x, extra) => text(id, content, LABEL, 7.6, 'muted',
  at('page', edge, x, HEAD_Y), { ...caps(7.6), parity, pages: 'body', ...extra });
const folio = (id, parity, edge, x, extra) => text(id, '{pageNumber}', DISPLAY, 8.5, 'glacier',
  at('page', edge, x, HEAD_Y), { fontWeight: 800, parity, pages: 'body', ...extra });
const header = { elements: [ // outer corners, over a hairline; never on the opener
  folio('verso-folio', 'even', 'top-left', OUTER),
  head('verso-title', '{title}', 'even', 'top-left', OUTER + 8),
  head('recto-title', '{chapterTitle}', 'odd', 'top-right', -(OUTER + 8), { align: 'right' }),
  folio('recto-folio', 'odd', 'top-right', -OUTER, { align: 'right' }),
  { kind: 'rule', id: 'hairline', pages: 'body', direction: 'horizontal', color: col('rule'),
    thickness: pt(0.5), placement: { ...at('container', 'top-left', 0, HAIRLINE),
      size: { width: 'fill', height: 'auto' } } },
] };
const footer = { elements: [ // the drop folio: on the opener only, centred 9 mm under the text
  text('drop-folio', '{pageNumber}', DISPLAY, 8.5, 'glacier', at('container', 'top', 0, 9),
    { fontWeight: 800, align: 'center', pages: 'opener' })] };

The opener is two boxes and four texts: a ribbon that hangs from the head with the chapter number at its foot, an ice slab that runs off the fore-edge, the kicker from the heading's topic attribute, and the title and standfirst chained under it. minHeight reserves the slab and at least 5 mm under it, rounded up to whole grid lines (about 7 mm here), so Figure 2.1 still fits the foot band of the same page. The running heads sit in the outer corners over a hairline in the rule colour, and pages: 'body' keeps them off the opener, which gets a drop folio instead.

#4 · Stop on an unknown id or an uncited figure

script.js · lines 289–310in full code
// The build lists every :ref and ::resource to an id no resource has in doc.contentWarnings
// (kind 'unknownResourceId'); each prints '?' on the page. A figure nobody names is never
// placed and raises no warning, so the pen reads the mentions with the engine's own parser;
// an embed needs double quotes (gotcha: resource-double-quotes).
function checkFigures(doc) {
  const [named, embedded] = [new Set(), new Set()];
  for (const block of parseMarkdown(markdown)) {
    if (block.type === 'resourceBlock' && block.resourceId) {
      named.add(block.resourceId);
      embedded.add(block.resourceId);
    }
    for (const span of block.spans) if (span.ref?.resourceId) named.add(span.ref.resourceId);
  }
  const unknown = (doc.contentWarnings ?? []).filter((w) => w.kind === 'unknownResourceId');
  const problems = [
    ...new Set(unknown.map((w) => `unknown id "${w.resourceId}"`)),
    ...resources.filter((r) => !named.has(r.id)).map((r) => `"${r.id}" is never cited`),
    ...resources.filter((r) => r.placement.position === 'here' && !embedded.has(r.id))
      .map((r) => `"${r.id}" is placed 'here' but no ::resource line embeds it`),
  ];
  if (problems.length) throw new Error(`Figures: ${problems.join('; ')}`);
}

A :ref or a ::resource to an id no resource has prints "?" and places nothing; the build records each one in doc.contentWarnings as unknownResourceId, with the id and its place in the source. A figure nobody mentions is never placed and raises no warning, so the check reads the Markdown with parseMarkdown, the engine's own parser, and compares the mentions with the figures. An unknown id, an uncited figure or a here figure with no ::resource line becomes one error before the pages are shown.

#5 · Start the count where the book is

script.js · lines 417–429in full code
for (const { id, svg: { fileId, width, height } } of resources) { // each under its svg.fileId
  const art = await dataUrl(PAINTINGS[id]);
  await loadSvg(fileId, svg(width, height, `<image href="${art}" width="${n2(width)}" `
    + `height="${n2(height)}" preserveAspectRatio="none"/>${DRAWINGS[id](width, height)}`));
}
// One chapter came before: figures number 2.1, 2.2… and the folios start at 27.
const continuation = { pageNumbering: { startAt: 27 }, // odd, to match the recto of page 1
  headings: { h1: 1, h2: 0, h3: 0, h4: 0, h5: 0, h6: 0 } }; // the next # is chapter 2
const doc = await buildDocumentWithFonts({ markdown, resources, continuation }, config(),
  { ...kitFonts(FONTS), text: words });
checkFigures(doc); // a wrong id stops here, and the viewer's bar says why
showPages(doc, { title: t({ en: 'Figures that float to where you cite them',
  es: 'Figuras que flotan hasta donde las citas' }) });

This is chapter 2 of a longer book, so the continuation records one chapter before it: figures numbered {h1}.{n} start at 2.1, and the folios at 27. On page 28 Figure 2.3 stands above Figure 2.2, which has the lower number because the text cites it first. Markdown's ![]() is stripped, so every figure is a resource whose SVG is registered under its svg.fileId before the build. Each placement follows from where the figure is cited: auto for 2.1, because the slab fills the head of the opener; bottom for the profile, which can still take the foot of the page that cites it; top for the column figures, which open the next free column heads; and top for 2.7 as well, which ends up at the foot of page 30 because a float stays inside its chapter.

The whole recipe

Sandbox
// ═══ Postext Cookbook · Nº 009 · Figures that float to where you cite them ═════════
// https://postext.dev/en/cookbook/figures-float-where-cited
// Code: MIT · Text: original (CC BY 4.0) · Figures: diffusion models, labels in code
// Fonts: Faustina, Montserrat, IBM Plex Sans Condensed (SIL OFL 1.1) · Needs postext ≥ 1.25.0
//
// Chapter 2 of a geomorphology textbook. Six of its seven figures float, each to the first
// free slot its placement allows, counting from the paragraph that first cites it. Figure 2.6
// is set where ::resource embeds it. The figures are numbered in order of first mention.
import {
  buildDocumentWithFonts, prepareFonts, renderPageToCanvas, registerResourceImage,
  inlineSvgFonts, parseMarkdown,
} from 'https://esm.sh/postext';

const LANG = 'en'; // @lang: the language of the sample document ('es' | 'en')
const RECIPE = 'figures-float-where-cited';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: eight named colours; the paintings were made to match them
const palette = {
  ink: '#1b2227', // text: a cold near-black
  glacier: '#34729a', // the accent: kicker, ribbon, caption labels, references, folios, water
  ice: '#e3f1f8', // the opener slab
  rock: '#5b5a57', // bedrock in the drawings
  moss: '#7d8f4e', // valley floors and pines
  rule: '#c6d3db', // the hairline under the running heads
  muted: '#5d6a72', // running heads, credit notes, the colophon
  paper: '#ffffff',
};
// A linked colour carries its hex and the palette entry it follows.
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
const colorPalette = [
  ...Object.entries(palette).map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } })),
  // The engine's defaults link to 'main-color' (#295aa3): pointing it at the accent keeps
  // that second blue off the page.
  { id: 'main-color', name: 'glacier (defaults)', value: { hex: palette.glacier, model: 'hex' } },
];
// #endregion
const TEXT = 'Faustina'; // one family each for text, display and labels
const DISPLAY = 'Montserrat';
const LABEL = 'IBM Plex Sans Condensed';
const LEAD = 13.4; // body leading in pt: the grid every float band snaps to
const [PAGE_W, PAGE_H, TOP, BOTTOM, INNER, OUTER, GUTTER] = [200, 250, 22, 20, 18, 14, 6]; // mm
const MEASURE = PAGE_W - INNER - OUTER; // 168 mm: the text block, and a page-wide figure
const COLUMN = (MEASURE - GUTTER) / 2; // 81 mm: a column, and a column figure

// #region captions: the type name in the document's language; bold label, italic description
const captions = () => ({
  // The built-in types take their names from the locale: 'Figure 2.3' and 'fig. 2.3' with

The composed script.js runs as it is: paste it into any page’s module script, or open the recipe on CodePen. Recipe folder on GitHub ↗ (opens in a new tab)

Variations

#Number the figures without the chapter

Drop the chapter from the numbers and the figures print 1 to 7; for one count through a whole book, lay the chapters out with buildBundle or pass each chapter the continuationAfter() of the one before.

-  inlineSvgFonts, parseMarkdown,
+  inlineSvgFonts, parseMarkdown, defaultResourceTypes,
@@
   locale: t({ en: 'en-us', es: 'es' }),
+  resourceTypes: defaultResourceTypes(LANG).map((type) => ({ ...type,
+    numberingTemplate: '{n}', resetOn: 'never' })),

#Set the captions above, on a bar

The caption moves over the figure onto a bar in the palette's ice blue and the credit line stays under the figure; refit the text, since both editions then run onto a fifth page.

   captionStyle: { // the text colour follows bodyText; the note is 0.85 × the caption size
+    position: 'above', backgroundEnabled: true, background: col('ice'),
     fontFamily: LABEL, fontSize: pt(8.3), gap: mm(2.2),

#Put a figure in the margin

A column-and-a-half page gives figures and their captions an outer channel the text never enters: see the textbook with a margin column.

#Float tables the same way

Tables are resources too, cited and placed by the same rules, and a long one splits across pages: see the technical datasheet.

Pitfalls

Pitfall

A 'top' float goes to the page after its citation unless it may head the citing page

By default a float never goes above its own reference, so a page-wide 'top' float cited on page N opens page N+1. Set placement.citingPage: true on the resource or its type's defaultPlacement (or layout.floatsAtCitingPage for the whole book, since postext 1.25) and it heads page N instead, the text above the reference moving down under it, when it fits within layout.maxTopFraction and the citing line stays on that page. It never heads a chapter's first page or a page after a forced break: there it still opens the next page, and 'auto' or 'bottom' can take the foot of the citing page. Figure placement →

Pitfall

::resource{id="…"} takes double quotes only

A block embed is recognised only as ::resource{id="…"} with double quotes; any other form stays in the text as a visible line. Figures exactly here →

Pitfall

No <marker> or filters in SVG art (raster fallback)

An SVG figure stays vector in the PDF only without <marker>, filters and masks; otherwise it falls back to a raster, and deeply nested filters can blank it in Chrome. Draw arrowheads as paths. Figures and tables as resources →

Sandbox check · unknownResourceId

Unknown resource

Why. A :ref or ::resource names an id no resource has; the reference prints "?" and nothing is placed.

Fix. Correct the id (double quotes only) or add the resource. Docs →

Credits

Text
Original prose, CC BY 4.0
Images
  • Figure 2.1: a V-shaped river valley and a U-shaped glacial valley · Generated With Diffusion Models · original
  • Figure 2.2: long profile of a valley glacier · Generated With Diffusion Models · original
  • Figure 2.3: a glacial cirque in section · Generated With Diffusion Models · original
  • Figure 2.4: abrasion at the base of the ice · Generated With Diffusion Models · original
  • Figure 2.5: plucking on a rock step · Generated With Diffusion Models · original
  • Figure 2.6: a roche moutonnée · Generated With Diffusion Models · original
  • Figure 2.7: lateral, medial and terminal moraines in plan · Generated With Diffusion Models · original
Fonts
Faustina (SIL OFL 1.1) · Montserrat (SIL OFL 1.1) · IBM Plex Sans Condensed (SIL OFL 1.1)
Sandbox