In short
A chapter from a physics textbook with a wide column of text and a narrow one by the outer edge. The narrow column holds diagrams and short notes beside the text they belong to.
What you'll build
Chapter 4 of Lever and Lens, an introductory physics textbook on a 210 × 275 mm page. The body text runs in one wide column and never enters the outer margin, a 53 mm channel. The chapter number, a green 4, sits in that channel level with the title, and the learning objectives go under it. Ray diagrams stack from the head of the channel, and key terms go in mint glosses beside the passages that define them. The figures that stay in the text column, on dark or light plates, have their captions in the margin, level with the foot of the figure. Only the prism panel crosses both columns. The margins mirror, so the channel is on the fore-edge of every page, on the right of a recto and on the left of a verso.
This recipe answers
- How do I make a column-and-a-half layout, with a wide text column and a narrow side column?
- How do I set margin notes or glosses beside the paragraph they explain?
- 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 set a caption beside a figure, or above a table on a caption bar?
- How do I number headings (1, 1.1, 1.1.1) and style each level differently?
The short answer
const layout = {
layoutType: 'oneAndHalf', // a wide main column and a narrow side column
sideColumnPercent: 30, // of the 176 mm content width: a 52.8 mm channel
sideColumnRole: 'floats', // no body text: side figures, side captions and side boxes only
sideColumnSide: 'outer', // right on a recto, left on a verso (the margins are mirrored)
gutterWidth: mm(7), // the text column keeps the rest: 176 − 52.8 − 7 = 116 mm
};
// A figure placed with span 'side' stacks in the channel from the head of the page that cites it,
// under the numeral on a chapter's first page.
const side = { span: 'side' };
// A figure left in the text column (the default span) sets its caption in the channel beside
// it; page-wide floats ignore captionSide and keep theirs underneath.
const resourceTypes = defaultResourceTypes(LANG).map((type) => (type.id !== 'figure' ? type
: { ...type, defaultPlacement: { captionSide: true } })); // the built-in types, in LANG
// A box fenced :::callout{type="term" span="side"} leaves the flow and lands in the channel at the
// height the text has reached: fence each gloss before the paragraph it should stand beside.
A float-only channel on the outer edge, and what goes into it
Ingredients
- Features
- Margin column for floatsSide captionsMargin notesColumn and a halfMirrored marginsCitations that place figuresFigure placementNumbered captionsFigures and tables as resourcesFigure and Table in your languageDesigned openersAnchoring design elementsHeading attributesNumbered headingsHeading stylesChapters that open on a rectoCallout boxesRunning heads and foliosHeads by page roleSemantic colour palette
- Type
- Merriweather, Merriweather Sans (SIL OFL 1.1)
- Assets
- None: every picture is drawn in code
Method
#1 · Give the margin to the floats
This step's code is the short answer above. In a column-and-a-half layout, sideColumnPercent: 30 gives the side column 30 % of the 176 mm content width (52.8 mm), and the text column keeps what is left after the 7 mm gutter (116 mm, about 75 characters of 9.3 pt Merriweather). sideColumnRole: 'floats' keeps the body text out of the side column, and sideColumnSide: 'outer' puts it on the outer side, which the mirrored margins switch from page to page. Figures go there with span: 'side'. A box with span="side" on its fence leaves the flow and goes into the channel at the height the text has reached, so each gloss starts level with the block that follows its fence.
#2 · Let the citation place each figure
const drawings = new Map(); // fileId → SVG markup, registered before the build
const figure = (id, { width, height, markup }, placement) => {
drawings.set(`${id}.svg`, markup);
return { id, typeId: 'figure', kind: 'svg', createdAt: 0, updatedAt: 0, caption: t(captions[id]),
altText: t(captions[id]), // read aloud in HTML and tagged PDF; the canvas does not use it
svg: { fileId: `${id}.svg`, width, height }, ...(placement && { placement }) };
};
const resources = [ // no placement: a main-column float, its caption in the channel
figure('burning-glass', burningGlass()),
figure('refraction', refraction(), side),
figure('critical-angle', criticalAngle(), side),
figure('fibre', fibre()),
figure('prism', prism(), { span: 'page', position: 'top' }), // across text column and channel
figure('principal-rays', principalRays()),
figure('diverging', diverging(), side),
];
The first :ref to a figure numbers it and places it where its placement says. A span: 'side' figure stacks from the head of the channel on the page that cites it, however far down the citation is, and moves to the next page when the rest of that channel is too short. Figures 4.2 and 4.3, both cited on page 88, stack down that page's channel with the critical-angle gloss between them. The prism is a page-wide top float cited on page 88, and a float never goes above its citation, so it opens page 89 across both columns. Figures 4.1, 4.4 and 4.6 stay in the text column and take captionSide from the figure type's defaultPlacement. They take the bottom slot of the column, so each caption sits level with the foot of its figure; in a top slot it would align with the figure's top.
#3 · Open the chapter in the margin
// Every element counts toward the opener's depth, the page-anchored numeral too (gotcha:
// opener-reserves-anchored). minHeight fixes that depth at nine lines of the grid, room for a
// one-line title, the rule and a four-line standfirst (41.2 mm), so the text starts on the same
// line in every such chapter, however short its standfirst and even with a smaller numeral. Kicker
// and numeral (40.6 mm) reach the ninth line too; a deeper opener grows past it, line by line.
const [KICKER, NUMERAL] = [8, 104]; // pt
const opener = {
enabled: true,
minHeight: pt(LEAD * 9), // 42.9 mm: the text starts on the eleventh line, after marginBottom
slot: {
elements: [
{ kind: 'text', id: 'title', content: '{titleText}', fontFamily: SANS, fontWeight: 800,
fontSize: pt(32), lineHeight: 1.05, color: col('ink'), align: 'left', overflow: 'wrap',
placement: { anchor: { to: 'container', edge: 'top-left' }, size: { width: 'fill' } } },
{ kind: 'rule', id: 'rule', direction: 'horizontal', thickness: pt(1), color: col('accent'),
placement: { anchor: { to: '#title', edge: 'below' }, offset: { y: mm(4) },
size: { width: 'fill' } } },
{ kind: 'text', id: 'lead', content: '{attr.lead}', fontFamily: SERIF, italic: true,
fontSize: pt(10.5), lineHeight: 1.45, color: col('ink'), align: 'left', overflow: 'wrap',
placement: { anchor: { to: '#rule', edge: 'below' }, offset: { y: mm(3.5) },
size: { width: 'fill' } } },
// The kicker hangs from the page's top-right corner, not from the heading: the channel lies
// outside the heading's column, and on the right only on a recto (so chapters open on one).
// The numeral hangs from the kicker.
{ kind: 'text', id: 'kicker', content: t({ en: 'Chapter', es: 'Capítulo' }), ...label,
fontSize: pt(KICKER), align: 'left', placement: { anchor: { to: 'page', edge: 'top-right' },
offset: { x: mm(-OUTER), y: mm(TOP) }, size: { width: mm(CHANNEL) } } },
{ kind: 'text', id: 'numeral', content: '{chapterNumber}', fontFamily: SANS, fontWeight: 800,
fontSize: pt(NUMERAL), lineHeight: 1, color: col('accent'), align: 'left',
placement: { anchor: { to: '#kicker', edge: 'below' }, offset: { y: mm(0.5) },
size: { width: mm(CHANNEL) } } },
],
},
};
The level-1 heading stays in the text column, where a design slot stacks its text, the rule and the standfirst; the kicker hangs from the page's top-right corner and the numeral from the kicker, both as wide as the channel. minHeight fixes the opener at nine grid lines (42.9 mm), enough for a one-line title, the rule and a four-line standfirst, so a shorter standfirst does not pull the text up. The kicker and the 104 pt numeral end 40.6 mm below the top margin, inside those nine lines, so they do not push the text down either. The channel is on the right only on a recto, so the H1 breaks to an odd page. The objectives box is fenced after the first paragraph, and no margin figure is cited before it, so it stands under the numeral (see Pitfalls).
#4 · Keep the folios on the channel's edge
const [HEAD_Y, FOOT_Y, HEAD_GAP] = [12.5, -12, 9]; // mm from the top and bottom trim; folio to head
// A text on the physical page: edge picks the corner, x and y are its offsets in mm.
const head = ({ edge, x, y = HEAD_Y, ...text }) => ({
kind: 'text', pages: 'body', ...label, color: col('muted'), ...text,
placement: { anchor: { to: 'page', edge }, offset: { x: mm(x), y: mm(y) } },
});
const folio = { content: '{pageNumber}', fontSize: pt(8.5), letterSpacing: pt(0),
color: col('accent') };
const verso = { parity: 'even', edge: 'top-left' }; // x counts in from the left edge
const recto = { parity: 'odd', edge: 'top-right' }; // x counts back from the right edge
const header = { elements: [
head({ id: 'verso-folio', ...verso, ...folio, x: OUTER }),
head({ id: 'verso-title', ...verso, content: '{title}', x: OUTER + HEAD_GAP }),
head({ id: 'recto-title', ...recto, x: -(OUTER + HEAD_GAP),
content: t({ en: 'Chapter {chapterNumber} · {chapterTitle}',
es: 'Capítulo {chapterNumber} · {chapterTitle}' }) }),
head({ id: 'recto-folio', ...recto, ...folio, x: -OUTER }),
] };
// A chapter's first page, always a recto, carries a drop folio at the foot of the channel instead.
const footer = { elements: [
head({ id: 'drop-folio', ...recto, ...folio, pages: 'opener', edge: 'bottom-right', x: -OUTER,
y: FOOT_Y }),
] };
Each element is anchored to the physical page and filtered by parity, so folio and running head sit on the same edge as the channel on both sides of the spread. pages: 'body' keeps them off the opener, which gets a drop folio at the foot of the channel instead.
#5 · Start the book at chapter 4
const continuation = { pageNumbering: { startAt: 87 }, // odd, like page 1: a recto
headings: { h1: 3, h2: 0, h3: 0, h4: 0, h5: 0, h6: 0 } }; // the next # is chapter 4
const doc = await buildDocumentWithFonts({ markdown, resources, continuation }, config(),
kitFonts(FONTS));
showPages(doc, { title: t({ en: 'Textbook with a margin column',
es: 'Libro de texto con columna al margen' }) });
These pages are chapter 4 of a longer book. The continuation sets the chapter counter to 3, so {chapterNumber} prints 4 and level 2's numberingTemplate: '{1}.{2}' numbers the sections 4.1 to 4.3; the figures run from 4.1 to 4.7. ## Questions {style="plain"} takes a headingStyles entry with numbered: false, so that heading has no number. The folios start at 87 because the first page is a recto, and a recto carries an odd folio.
#6 · Name the colours once
const palette = {
ink: '#1a222d', // text, and the dark panels of figures 4.1, 4.4 and 4.5
accent: '#17774f', // the only accent colour: numerals, folios, section headings, labels
ray: '#f2a516', // light rays in every diagram
glass: '#cfe6dd', // glass in the diagrams
tint: '#edf5f1', // the key-term glosses and the light plate of a construction diagram
muted: '#5b6863', // running heads, the normals in the diagrams, the colophon
paper: '#ffffff',
};
// A colour carries its id and its hex. The diagrams read `palette` as well, so retint the
// chapter by editing it: the text, the designs and the drawings change together.
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': point it at the accent, so nothing prints blue.
{ id: 'main-color', name: 'accent (defaults)', value: { hex: palette.accent, model: 'hex' } },
];
Every colour in the configuration links to a palette entry and also carries its hex, which col() copies from the same object. To retint the chapter, edit palette: the diagrams read the same object, so their glass, rays, dark panels and light plate change along with the numerals, labels and glosses. main-color points at the accent, so any default colour in the text styles that the configuration leaves unset prints green, not the engine's blue.
The whole recipe
// ═══ Postext Cookbook · Nº 001 · Textbook with a margin column ═══════════════════
// https://postext.dev/en/cookbook/textbook-margin-column
// Code: MIT · Text: original (CC BY 4.0) · Diagrams: generated in code (CC BY 4.0)
// Fonts: Merriweather, Merriweather Sans (SIL OFL 1.1) · Needs postext ≥ 1.25.0
// A chapter of a physics textbook in the column-and-a-half layout: the body text keeps to
// the main column, and the outer margin is a channel for diagrams, captions and glosses.
import {
buildDocumentWithFonts, renderPageToCanvas, registerResourceImage, defaultResourceTypes,
} from 'https://esm.sh/postext';
const LANG = 'en'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'textbook-margin-column';
// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: semantic colours, each linked by id and written out in hex
const palette = {
ink: '#1a222d', // text, and the dark panels of figures 4.1, 4.4 and 4.5
accent: '#17774f', // the only accent colour: numerals, folios, section headings, labels
ray: '#f2a516', // light rays in every diagram
glass: '#cfe6dd', // glass in the diagrams
tint: '#edf5f1', // the key-term glosses and the light plate of a construction diagram
muted: '#5b6863', // running heads, the normals in the diagrams, the colophon
paper: '#ffffff',
};
// A colour carries its id and its hex. The diagrams read `palette` as well, so retint the
// chapter by editing it: the text, the designs and the drawings change together.
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': point it at the accent, so nothing prints blue.
{ id: 'main-color', name: 'accent (defaults)', value: { hex: palette.accent, model: 'hex' } },
];
// #endregion
// The page in mm, named once: the channel, the opener and the running heads derive from it.
const [TRIM_W, TRIM_H] = [210, 275];
const [TOP, BOTTOM, INNER, OUTER] = [24, 22, 20, 14]; // inner and outer swap on a verso
const LEAD = 13.5; // body leading in pt
const [SERIF, SANS] = ['Merriweather', 'Merriweather Sans'];
// #region answer: a float-only channel on the outer edge, and what goes into it
const layout = {
layoutType: 'oneAndHalf', // a wide main column and a narrow side column
sideColumnPercent: 30, // of the 176 mm content width: a 52.8 mm channel
sideColumnRole: 'floats', // no body text: side figures, side captions and side boxes only
sideColumnSide: 'outer', // right on a recto, left on a verso (the margins are mirrored)
gutterWidth: mm(7), // the text column keeps the rest: 176 − 52.8 − 7 = 116 mm
};
// A figure placed with span 'side' stacks in the channel from the head of the page that cites it,
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
#Keep the captions under the figures
With the figure type's plain defaults, the captions of figures 4.1, 4.4 and 4.6 take lines from the text column, and the channel holds only diagrams and glosses.
-const resourceTypes = defaultResourceTypes(LANG).map((type) => (type.id !== 'figure' ? type
- : { ...type, defaultPlacement: { captionSide: true } })); // the built-in types, in LANG
+const resourceTypes = defaultResourceTypes(LANG); // what the engine uses when none are set#Put the channel on the right of every page
For a document read one page at a time on screen, stop mirroring the margins and move the verso's folio and running head to the right-hand edge; chapters can then open on either page.
- sideColumnSide: 'outer', // right on a recto, left on a verso (the margins are mirrored)
+ sideColumnSide: 'right', // what 'outer' means anyway once the margins stop mirroring
- bottom: mm(BOTTOM), left: mm(INNER), right: mm(OUTER), mirror: true } }, // left: recto's inner
+ bottom: mm(BOTTOM), left: mm(INNER), right: mm(OUTER), mirror: false } },
- { level: 1, breakBefore: { enabled: true, parity: 'odd' }, marginBottom: pt(LEAD),
+ { level: 1, breakBefore: { enabled: true, parity: 'any' }, marginBottom: pt(LEAD),
-const verso = { parity: 'even', edge: 'top-left' }; // x counts in from the left edge
+const verso = { parity: 'even', edge: 'top-right' };
- head({ id: 'verso-folio', ...verso, ...folio, x: OUTER }),
- head({ id: 'verso-title', ...verso, content: '{title}', x: OUTER + HEAD_GAP }),
+ head({ id: 'verso-folio', ...verso, ...folio, x: -OUTER }),
+ head({ id: 'verso-title', ...verso, content: '{title}', x: -(OUTER + HEAD_GAP) }),
- head({ id: 'drop-folio', ...recto, ...folio, pages: 'opener', edge: 'bottom-right', x: -OUTER,
+ head({ id: 'drop-folio', ...folio, pages: 'opener', edge: 'bottom-right', x: -OUTER,#Open the chapter under a colour band
Chapter opener on a full-bleed band bleeds a colour band off the top of the page and sets the title and a 168 pt chapter number on it.
Pitfalls
Pitfall
Side boxes never float: they wait for room
A span: 'side' box does not float: it sits beside the block it follows and, when the margin channel is full, waits for the next page. Put each gloss right after the paragraph it explains. When the chapter ends with boxes still waiting, each takes the side column of a page after the text, in fence order, and the build reports it (afterText); up to postext 1.24 only one such page was opened and the boxes left were dropped without a warning. Margin notes →
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
An opener reserves height down to its lowest page-anchored element
An advanced-design opener reserves the height of its lowest element, and page- or bleed-anchored elements below the heading count too, so decoration at the foot of the page pushes the text to the next page. Give such an element reserve: false (since postext 1.5): it is painted where it is anchored and reserves nothing. Elements that follow the band itself (anchored to its foot, or 'fill' tall) never set its height. Designed openers →
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 →
- Figures and glosses stack in the channel in the order the text reaches them, never side by side. The critical-angle gloss is fenced after the Snell's-law paragraph and before the paragraph that cites figure 4.3, so on page 88 it stacks between figures 4.2 and 4.3, beside the paragraph that introduces the term. Fenced after that citation, it would land under figure 4.3.
- On a chapter's first page, side figures stack under the kicker and the numeral. A figure cited in the first paragraph takes that place and moves the objectives box down the channel, so this chapter cites its first margin figure after the box.
Credits
- Recipe
- Ignacio Ferro
- Text
- Original prose, CC BY 4.0
- Fonts
- Merriweather (SIL OFL 1.1) · Merriweather Sans (SIL OFL 1.1)
Edit this write-up ↗ (opens in a new tab)Recipe folder on GitHub ↗ (opens in a new tab)


