Skip to main content
Recipe number 8

Cookbook · Chapter 12 · Textbooks

A colour-coded family of textbook boxes

Six kinds of textbook box in three colours, told apart by a stripe with an icon, a badge, a numbered tab, a strip of pictograms or a marker outside the frame.

pp. 28–29 · 2–3 of 3

  • Trim 210 × 280 mm
  • 2 columns, 8 mm gutter
  • Noto Serif 9.4/13.4
  • Barlow Semi Condensed
  • Lexend
  • 3 pages
  • Level
  • Postext 1.57.1
  • Laid out in 99 ms
  • 179 lines of code

In short

A chapter from a biology textbook with six kinds of boxes, such as warnings and lab notes. Each kind has its own colour and symbol, so students can tell them apart at a glance.

What you'll build

Chapter 2 of Living Matter, an upper-secondary biology textbook on a 210 × 280 mm page, opens under a drawing of a cell cut by the page's top corner, with the chapter number in its core. Six kinds of box follow in three colours, each with a device of its own, so a student can tell an objective from a warning before reading it. Magenta marks the learning objectives, set on a stripe that holds a target, and the self-check, which has a ticked tile outside its frame. Green marks the study tip, set beside a thin rule capped by a bulb badge, and the lab box with its three safety pictograms. The warning is amber, with an alert badge on its outer corner. BOX 2.1 is lavender under a black tab and a flask. Bold terms take their box's colour, magenta in BOX 2.1.

This recipe answers

  • How do I make note, tip or warning boxes with an icon, a coloured stripe and rounded corners?
  • How do I add a numbered tab ("BOX 1-1"), a corner icon, or a margin icon with a rule?
  • How do I colour key terms (bold or italic) in the body or inside boxes?

The short answer

script.js · lines 41–62in full code
// box(id, hue, device) is the shared base: the hue colours the title, bullets and key terms.
const TAB = 5, BADGE = 7.4; // in mm: the tab's height (and offset), the warning badge's size
const calloutStyles = [
  // The first style is also the one a missing or misspelt type falls back to.
  box('objectives', 'band', { title: t({ en: 'In this chapter', es: 'En este capítulo' }),
    background: col('tintBand'), stripe: { enabled: true, width: mm(7.5), color: col('band') },
    icon: icon('target', 5) }), // on a side stripe (left by default) the icon is centred on it
  box('feature', 'band', { background: col('mist'),
    titleStyle: { fontFamily: 'Lexend', fontSize: pt(10.5), color: col('ink'), gap: mm(1.6) },
    // Printed only where the fence has label="…": the tab, the flask beside it, a rule to them.
    label: { fontFamily: LABEL, fontSize: pt(8), color: col('paper'), background: col('ink'),
      position: 'top-left', // this verso's outer corner, above the badge ('top-right' by default)
      height: mm(TAB), offset: mm(TAB), paddingX: mm(2.3), // offset = height: on the top edge
      icon: { resourceId: 'flask', width: mm(4.4), gap: mm(1.2) },
      rule: { enabled: true, color: col('ink'), width: pt(1.2) } } }),
  box('warning', 'warnInk', { background: col('tintWarn'), borderRadius: mm(1.4),
    border: { enabled: true, color: col('warn'), width: pt(0.75) },
    // The badge hangs half past the outer corner: sides of half badge + GAP align the title.
    padding: { top: mm(2.8), right: mm(BADGE / 2 + GAP), bottom: mm(3.2),
      left: mm(BADGE / 2 + GAP) },
    icon: icon('caution', BADGE, { position: 'corner', cornerSide: 'outer' }) }),
]; // straight into config(), followed by the 'more' styles

Three devices: an icon on a wide stripe, a numbered tab, an outer badge

Ingredients

Type
Noto Serif, Lexend, Barlow Semi Condensed (SIL OFL 1.1)
Assets
None: every picture is drawn in code

Method

#1 · Give every kind of box a colour

script.js · lines 14–22in full code
const palette = { ink: '#1f2430', paper: '#ffffff', // text; type on stripes and tabs
  band: '#ab2e78', tintBand: '#fae3ef', // the chapter's magenta: opener, objectives, self-check
  tip: '#25734a', tintTip: '#e2f0e7', // study tips and lab work
  warn: '#e39422', tintWarn: '#fcefd8', warnInk: '#94540a', // frame and badge; tint; its type
  mist: '#e8e3f0', rule: '#dccfd8', muted: '#675e66' }; // feature box; lines in drawings; heads
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
// The engine's defaults link to 'main-color': point it at the band, so nothing prints blue.
const colorPalette = Object.entries({ ...palette, 'main-color': palette.band })
  .map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } }));

Six kinds of box share three hues: magenta for the objectives and the self-check, green for the study tip and the lab, amber for the warning. BOX 2.1 has a lavender fill and uses magenta for its key terms. Each hue has a pale tint for fills, and every colour setting links to a palette entry, so changing a hue means editing one value. Type this small needs a contrast of 4.5:1. Magenta on the lavender reaches 4.9:1, but amber on the warning's fill only 2.2:1, so the warning keeps amber for its frame and badge and sets its title and key terms in warnInk, a darker amber at 5.2:1.

#2 · Share everything else

script.js · lines 28–37in full code
const box = (id, hue, device) => ({ id, marginTop: pt(LEAD), marginBottom: pt(LEAD / 2),
  padding: { top: mm(2.8), right: mm(3.4), bottom: mm(3.2), left: mm(3.4) },
  titleStyle: { fontFamily: LABEL, fontSize: pt(8.5), color: col(hue), // bold by default
    textTransform: 'uppercase', letterSpacing: pt(1.4), gap: mm(GAP) },
  body: { fontFamily: LABEL, fontSize: pt(9.6), lineHeight: pt(12.6), color: col('ink'),
    boldColor: col(hue), textAlign: 'left', firstLineIndent: pt(0), paragraphSpacing: true },
  lists: { color: col(hue), gap: mm(2.2), itemSpacing: pt(2.4) }, // bullets and numbers
  ...device }); // the kind's title, fill and device: its spread wins over the base
// An SVG or bitmap resource, fitted into a square of that size (width × size with `width`).
const icon = (id, size, more) => ({ kind: 'resource', resourceId: id, size: mm(size), ...more });

box() holds the settings every box shares: margins, padding, title and body type, list spacing. Its hue argument colours the title, the bullets and numbers, and the bold runs. body.boldColor turns fluid mosaic model magenta in the objectives and cell wall amber-brown in the warning; bold in the running text stays ink (typography inside a box). Declaring calloutStyles replaces the only style the engine ships, a grey box called note. A fence whose type is missing or misspelt takes the first style, so the list opens with the objectives, which every chapter has.

#3 · Stripe, tab and badge

The code is the short answer above. The objectives' stripe is 7.5 mm wide and its target 5 mm, so the icon sits inside the colour with room on either side. The tab's offset equals its height, which stands the tab on the top edge of the box, clear of the title. 'top-left' is the outer corner of this verso; the flask follows the tab, and the rule runs along the top edge from the flask to the far corner. position: 'corner' hangs the warning's badge half its width past the edge, and cornerSide: 'outer' sends it to the fore-edge side, the left on this verso. On that side the engine indents the title to clear the badge unless the padding already covers half the badge plus the title gap, so the warning pads both sides by BADGE / 2 + GAP and its title lines up with its text. Only this box has a borderRadius: it is the one box with a frame, and a 1.4 mm radius softens its corners. A radius on a striped box would round the stripe's outer corners with it (callout styles).

#4 · Three more devices

script.js · lines 66–79in full code
const BULB = 6.4; // the study tip's badge in mm: the text clears it
const moreStyles = [
  box('tip', 'tip', { title: t({ en: 'Study tip', es: 'Para recordar' }),
    backgroundEnabled: false, stripe: { enabled: true, width: pt(2.5), color: col('tip') },
    // A stripe narrower than its icon: the badge sits on it at the top and hides it there.
    padding: { top: mm(0.6), right: mm(0), bottom: mm(0.6), left: mm(BULB / 2 + 2) },
    icon: icon('bulb', BULB) }),
  box('safety', 'tip', { background: col('tintTip'), marginTop: pt(4), // under its heading
    icon: icon('safety', 7, { width: mm(24.5), align: 'center' }) }), // 3 pictograms, 1 image
  box('check', 'band', { background: col('tintBand'),
    // Outside the frame: [marker][rule][gap][box], the rule as tall as the box.
    marker: { kind: 'resource', resourceId: 'check', size: mm(7), align: 'top', gap: mm(3),
      rule: { enabled: true, color: col('band'), width: pt(0.75) } } }),
];

The study tip's stripe is 2.5 pt wide against a 6.4 mm bulb badge, so it prints as a thin rule with the badge over its top end; a left padding of half the badge plus 2 mm keeps the text clear of the bulb. icon.width fits a picture into a wide box instead of a square, so the three safety pictograms, drawn as one 24.5 mm image, make the lab box's icon column, centred on its text. The self-check's marker sits outside the frame, in the order marker, rule, gap, box. Its square tile on a 0.75 pt rule sets it apart from the study tip, whose badge is round. The fence adds span="page" placement="bottom" to float the self-check to the foot of page 29.

#5 · Icons are resources

script.js · lines 240–265in full code
const svgResource = (id, width, height, extra) => ({ id, typeId: 'figure', kind: 'svg',
  svg: { fileId: `${id}.svg`, width, height }, createdAt: 0, updatedAt: 0, ...extra });
const pageTop = { position: 'top', span: 'page' }; // a 'top' float opens the page after its :ref
const resources = [
  // Uncited, so never placed as figures: the box styles and the opener use them by id.
  ...['target', 'bulb', 'caution', 'check'].map((id) => svgResource(id, 240, 240)),
  svgResource('flask', 200, 240), svgResource('safety', 760, 240), svgResource('cell', 2000, 2000),
  svgResource('mosaic', 3480, 1240, { placement: pageTop, caption: t({
    en: 'The fluid mosaic: magenta phospholipids, green proteins, an amber carrier with its '
      + 'glucose, grey cholesterol, amber sugars.', // one line: the page is wide
    es: 'El mosaico fluido: fosfolípidos magenta, proteínas verdes, transportadora ámbar con su '
      + 'glucosa, colesterol gris, azúcares ámbar.' }),
    altText: t({ en: 'A cell membrane in section', es: 'Una membrana celular en sección' }) }),
  svgResource('fusion', 1800, 500, { placement: { position: 'here' }, caption: t({
    en: 'Mouse proteins in green, human proteins in magenta (the red dye): the two cells, the '
      + 'hybrid just after fusion and the same hybrid 40 minutes later.',
    es: 'En verde, las proteínas de ratón; en magenta, las humanas (el colorante rojo): las dos '
      + 'células, el híbrido recién fusionado y el mismo híbrido 40 minutos después.' }),
    altText: t({ en: 'Two cells fusing into a hybrid', es: 'Dos células que se fusionan' }) }),
  svgResource('osmosis', 3480, 860, { placement: pageTop, caption: t({
    en: 'Red blood cells in a hypertonic, an isotonic and a hypotonic solution. Arrows show the '
      + 'net flow of water.',
    es: 'Glóbulos rojos en una disolución hipertónica, una isotónica y una hipotónica. Las flechas '
      + 'indican el flujo neto de agua.' }),
    altText: t({ en: 'Blood cells in three solutions', es: 'Glóbulos rojos en tres medios' }) }),
];

Every icon, the flask beside the tab and the opener's cell are SVG resources declared with the content and registered by file id. A style names them by resource id, and because the text never cites them, none of them becomes a numbered figure. Glyphs such as ✓ or ☞ would be shorter to write, but the Fontsource latin files the pages load do not have them: the canvas would borrow them from a system font, and a PDF would drop them. The drawings carry no words either: the captions name the colours, so one drawing serves both editions.

#6 · Open the chapter with a cell

script.js · lines 83–102in full code
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 }); // an opener's texts wrap by default
const below = (id, y, width) => ({ anchor: { to: `#${id}`, edge: 'below' },
  offset: { y: mm(y) }, size: { width: mm(width) } });
const chapter = t({ en: 'Chapter {chapterNumber}', es: 'Capítulo {chapterNumber}' });
const opener = { enabled: true, minHeight: mm(66), slot: { elements: [
  { kind: 'image', id: 'cell', resourceId: 'cell', placement: { anchor: { to: 'page',
    edge: 'top-right' }, offset: { x: mm(58), y: mm(-71) }, size: { width: mm(150) } } },
  text('numeral', '{chapterNumber}', 'Lexend', 118, 'paper', { anchor: { to: 'page',
    edge: 'top-right' }, offset: { x: mm(-OUTER), y: mm(14) } },
    { fontWeight: 800, lineHeight: 1, align: 'right' }),
  text('kicker', `${chapter} · {attr.unit}`, LABEL, 9, 'band', { anchor: { to: 'container',
    edge: 'top-left' }, offset: { y: mm(3) } },
    { fontWeight: 700, letterSpacing: pt(1.8), textTransform: 'uppercase' }),
  text('title', '{titleText}', 'Lexend', 34, 'ink', below('kicker', 2.5, 112),
    { fontWeight: 700, lineHeight: 1.04 }),
  text('lead', '{attr.lead}', 'Noto Serif', 10.5, 'ink', below('title', 5, 98),
    { italic: true, lineHeight: 1.42 }),
] } };

The cell is an image element anchored to the page's top-right corner and pushed past it, so mostly its lower-left quarter shows, and the numeral sits in its core. Both stay inside the 66 mm that minHeight reserves for the opener. The kicker and the standfirst come from the heading line, # Cells and \\ Membranes {unit="The cell" lead="…"}, and the \\ breaks the title only in the opener.

The whole recipe

Sandbox
// ═══ Postext Cookbook · Nº 008 · A family of textbook boxes ═══════════════════════
// https://postext.dev/en/cookbook/textbook-box-family
// Code: MIT · Text: original (CC BY 4.0) · Drawings and icons: generated in code (CC BY 4.0)
// Fonts: Noto Serif, Lexend, Barlow Semi Condensed (SIL OFL 1.1) · Needs postext ≥ 1.25.0
import {
  buildDocumentWithFonts, prepareFonts, renderPageToCanvas, registerResourceImage,
} from 'https://esm.sh/postext';

const LANG = 'en'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'textbook-box-family';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: three hues for six kinds of box; everything links to an entry
const palette = { ink: '#1f2430', paper: '#ffffff', // text; type on stripes and tabs
  band: '#ab2e78', tintBand: '#fae3ef', // the chapter's magenta: opener, objectives, self-check
  tip: '#25734a', tintTip: '#e2f0e7', // study tips and lab work
  warn: '#e39422', tintWarn: '#fcefd8', warnInk: '#94540a', // frame and badge; tint; its type
  mist: '#e8e3f0', rule: '#dccfd8', muted: '#675e66' }; // feature box; lines in drawings; heads
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
// The engine's defaults link to 'main-color': point it at the band, so nothing prints blue.
const colorPalette = Object.entries({ ...palette, 'main-color': palette.band })
  .map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } }));
// #endregion
// Label face (box text and titles, tabs, captions, heads); leading in pt; outer margin in mm
const LABEL = 'Barlow Semi Condensed', LEAD = 13.4, OUTER = 16, GAP = 1.5; // GAP: title gap, mm

// #region base: what every box shares; each kind brings its colour and its one device
const box = (id, hue, device) => ({ id, marginTop: pt(LEAD), marginBottom: pt(LEAD / 2),
  padding: { top: mm(2.8), right: mm(3.4), bottom: mm(3.2), left: mm(3.4) },
  titleStyle: { fontFamily: LABEL, fontSize: pt(8.5), color: col(hue), // bold by default
    textTransform: 'uppercase', letterSpacing: pt(1.4), gap: mm(GAP) },
  body: { fontFamily: LABEL, fontSize: pt(9.6), lineHeight: pt(12.6), color: col('ink'),
    boldColor: col(hue), textAlign: 'left', firstLineIndent: pt(0), paragraphSpacing: true },
  lists: { color: col(hue), gap: mm(2.2), itemSpacing: pt(2.4) }, // bullets and numbers
  ...device }); // the kind's title, fill and device: its spread wins over the base
// An SVG or bitmap resource, fitted into a square of that size (width × size with `width`).
const icon = (id, size, more) => ({ kind: 'resource', resourceId: id, size: mm(size), ...more });
// #endregion

// #region answer: three devices: an icon on a wide stripe, a numbered tab, an outer badge
// box(id, hue, device) is the shared base: the hue colours the title, bullets and key terms.
const TAB = 5, BADGE = 7.4; // in mm: the tab's height (and offset), the warning badge's size
const calloutStyles = [
  // The first style is also the one a missing or misspelt type falls back to.
  box('objectives', 'band', { title: t({ en: 'In this chapter', es: 'En este capítulo' }),
    background: col('tintBand'), stripe: { enabled: true, width: mm(7.5), color: col('band') },
    icon: icon('target', 5) }), // on a side stripe (left by default) the icon is centred on it
  box('feature', 'band', { background: col('mist'),

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

#Set a box across both columns

span="page" on a fence sets any kind of box across both columns; BOX 2.1 also nests a :::columns group to put its figure beside its text.

-:::callout{type="warning" title="Membrane or wall?"}
+:::callout{type="warning" title="Membrane or wall?" span="page"}

#Hang the badge on the spine side

'inner' moves the badge to the spine side, left on a recto and right on a verso; leave room on that side for the half that hangs outside the box.

-    icon: icon('caution', BADGE, { position: 'corner', cornerSide: 'outer' }) }),
+    icon: icon('caution', BADGE, { position: 'corner', cornerSide: 'inner' }) }),

#Stand the tab on the right corner

'top-right', the default, mirrors the whole label: the tab moves to the right corner, the flask to its left, and the rule runs in from the left.

-      position: 'top-left', // this verso's outer corner, above the badge ('top-right' by default)
+      position: 'top-right',

Pitfalls

Pitfall

Fontsource files cover letters, not symbols

The kit embeds a face's Fontsource latin file, plus its latin-ext file for č, ł, † and its greek file for α, χ (in a family that ships one: Lora and Gelasio do not), when the text sets them, on screen and in the PDF. Symbols such as →, ≈, ✓ and ★ are in none of those files and go missing in the PDF: draw them, set them as maths, or choose a face whose files hold them. Fonts embedded in the PDF →

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

Page 1 is a recto: plan pages with physical numbers

Page 1 is a right-hand page and page 2 the first verso, so plan spreads with physical page numbers: an opener on an even page faces the odd page after it. Page and column breaks →

Layout warning · unknownCalloutType

Unknown callout type

Why. A :::callout names a type that calloutStyles does not define, so it silently takes the first style.

Fix. Define the style or correct the type attribute. Docs →

  • The tab prints only when the fence has label="BOX 2.1" and the style has a label object. A style without one ignores the attribute.
  • Postext does not number boxes. The label is the fence's literal text, so you type each number, BOX 2.1, BOX 2.2, by hand.
  • A corner badge hangs half its width past the side of the box, into the margin on the outer side of the page. In the other column of the same page it hangs into the gutter, so keep boxes with badges in the outer column or leave them room.
  • A box's lists.color colours its bullets and the numbers of its ordered lists alike, so the numbered steps and questions here print in their box's hue. To colour only a box's bullets, leave lists.color out of its style and set unorderedLists.color for the document; the numbers then keep orderedLists.color.

Credits

Text
Original prose, CC BY 4.0
Fonts
Noto Serif (SIL OFL 1.1) · Lexend (SIL OFL 1.1) · Barlow Semi Condensed (SIL OFL 1.1)
Sandbox