Коротко
Школьное издание классического испанского романа, в две колонки. Показано, как ставить каждую сноску внизу колонки, где она упомянута, чтобы читатель не листал страницы.
Что получится
Школьное издание «Ласарильо с Тормеса», 210 × 280 мм, две колонки EB Garamond: пролог и начало первого трактата, где Ласаро рождается на мельнице на Тормесе и уходит в мир со слепым. Сноски объясняют то, что читатель 1554 года знал, а нынешний не знает: деревню Техарес, поход на остров Лос-Хельвес, каменного быка на мосту Саламанки. Каждая стоит внизу колонки, которая на неё ссылается, набрана мельче под короткой тёмно-красной линейкой, и взгляд спускается от номера к сноске и обратно, не переворачивая страницы. Английское издание несёт собственные сноски Клементса Маркхэма из его перевода 1908 года.
Рецепт отвечает на вопросы
- Как сделать сноски?
Короткий ответ
// In the Markdown: `Tejares,[^9]` cites a note (the id may be a word: `[^tejares]`), and
// a paragraph that opens with `[^9]:` anywhere in the chapter defines it. The engine
// numbers the notes in order of citation and keeps each note in the column of the line
// that cites it: a line whose note does not fit under it moves on with the note.
const footnotes = () => ({
placement: options.placement, // 'column' (the foot of the citing column) or 'chapterEnd'
numbering: options.numbering, // 'chapter': 1, 2, 3… again under every chapter heading
fontSize: pt(8.5), // off the baseline grid: the notes stack up from the column's foot
lineHeight: pt(10.5),
hangingIndent: em(0.9), // turnover lines align past the number
spaceBetween: pt(1.5),
separator: { width: 0.25, lineWidth: pt(0.5), color: col('oxblood') },
});
Ингредиенты
- Возможности
- СноскиВерхние и нижние индексыОдна или две колонкиОформленные начальные полосыАтрибуты заголовковКолонтитулы и колонцифрыЗеркальные поляКолонтитулы по роли страницыСтили абзацевСемантическая палитраЦвет бумагиВисячие и короткие концевые строкиЭкспорт в PDFДоступный PDF с тегами
- Также применяет
- Шапка главы на всю ширинуШрифты, встроенные в PDF
- Шрифты
- EB Garamond, Bodoni Moda, IBM Plex Sans Condensed (SIL OFL 1.1)
- Материалы
- Нет: все иллюстрации рисует код
Порядок работы
#1 · Ссылайтесь на сноску там, где она нужна, а определяйте где угодно
Настройка приведена выше, в коротком ответе; остальное — Markdown. natives of Tejares,[^9] печатает надстрочный номер, прижатый к запятой, а абзац, который начинается с [^9]:, хранит сноску. Определения выходят из потока, где бы их ни записали, поэтому в этом примере они все в конце главы, как стояли сноски Маркхэма в исходном файле. Номера следуют порядку ссылок, поэтому id в Markdown могут быть словами ([^tejares] в испанском издании), и перенумерация главы никогда не требует правки сносок.
#2 · Оставляйте колонке место для её сносок
Прежде чем поставить строку, вёрстка добавляет высоту сносок, на которые эта строка ссылается впервые, и линейку, если сноска первая в колонке. Строка, чья сноска под ней не помещается, переходит в следующую колонку вместе со своим абзацем, по правилам висячих строк (widow и orphan), поэтому номер никогда не указывает на сноску в другой колонке. Сноски складываются снизу вверх своим кеглем и интерлиньяжем, вне сетки базовых линий, а текст над ними остаётся на ней; выравнивание колонок считает только текст.
#3 · Опустите каждую начальную полосу на одну линию
const opener = {
enabled: true,
// The sink holds a two-line title and its rule, with ~8 mm to the first line of text,
// so every chapter starts on the same grid line whatever its title's length.
minHeight: pt(LEAD * 10),
slot: { elements: [
{ kind: 'text', id: 'kicker', content: '{attr.kicker}', ...label, fontSize: pt(8.5),
letterSpacing: pt(1.8), color: col('oxblood'), align: 'center',
placement: at('container', 'top', 0, 7) },
{ kind: 'text', id: 'title', content: '{titleText}', fontFamily: 'Bodoni Moda', italic: true,
fontSize: pt(26), lineHeight: 1.1, color: col('ink'), align: 'center',
overflow: 'wrap', // design text ends in an ellipsis by default
placement: { ...at('container', 'top-left', 0, 13),
size: { width: 'fill', height: 'auto' } } },
{ kind: 'rule', id: 'rule', direction: 'horizontal', thickness: pt(0.75), color: col('oxblood'),
placement: { anchor: { to: '#title', edge: 'below' }, // a rule starts at the box's left
offset: { x: mm((MEASURE - 14) / 2), y: mm(4.5) }, size: { width: mm(14) } } },
] },
};
Начальная полоса охватывает обе колонки и рисует надзаголовок главы из атрибута kicker заголовка. minHeight резервирует десять линий сетки, чего хватает на заголовок Bodoni в две строки с линейкой, поэтому текст каждой главы начинается с одной линии, а линейка никогда не попадает на первую строку текста.
#4 · Книга на левой полосе, глава на правой
const head = (id, content, parity, edge, x, extra = {}) => ({
kind: 'text', id, content, parity, pages: 'body', // never on openers
...label, fontSize: pt(7.5), letterSpacing: pt(1.3), color: col('muted'),
placement: at('page', edge, x, 13), ...extra,
});
const folio = { color: col('oxblood') };
const header = { elements: [
head('verso-folio', '{pageNumber}', 'even', 'top-left', MARGIN.outer,
{ ...folio, align: 'left' }),
head('verso-title', '{title}', 'even', 'top-left', MARGIN.outer + 9, { align: 'left' }),
head('recto-title', '{chapterTitle}', 'odd', 'top-right', -(MARGIN.outer + 9),
{ align: 'right', overflow: 'ellipsis' }),
head('recto-folio', '{pageNumber}', 'odd', 'top-right', -MARGIN.outer,
{ ...folio, align: 'right' }),
] };
// Openers carry a drop folio instead, centred under the text block.
const footer = { elements: [{ ...head('drop-folio', '{pageNumber}', 'all', 'bottom', 0,
{ ...folio, align: 'center', placement: at('page', 'bottom', 0, -11) }), pages: 'opener' }] };
Колонтитулы привязаны к странице по чётности, колонцифра у наружного края; pages: 'body' убирает их с начальных полос, где колонцифра центрирована внизу. Длинное название главы обрывается многоточием на 120 мм и не заходит на колонцифру.
#5 · Попробуйте другие размещения
const CHOICES = {
columns: [[2, t({ en: 'Two columns', es: 'Dos columnas' })],
[1, t({ en: 'One column', es: 'Una columna' })]],
placement: [['column', t({ en: 'Column foot', es: 'Pie de columna' })],
['chapterEnd', t({ en: 'End of chapter', es: 'Final del capítulo' })]],
numbering: [['chapter', t({ en: 'Per chapter', es: 'Por capítulo' })],
['document', t({ en: 'Continuous', es: 'Continua' })]],
};
const bar = document.createElement('form');
bar.id = 'options';
bar.ariaLabel = t({ en: 'Footnote options', es: 'Opciones de las notas' });
for (const [key, choices] of Object.entries(CHOICES)) {
const group = bar.appendChild(document.createElement('fieldset'));
for (const [value, text] of choices) {
const input = Object.assign(document.createElement('input'), { type: 'radio', name: key,
value: String(value), checked: options[key] === value });
const item = group.appendChild(document.createElement('label'));
item.append(input, text);
}
}
bar.addEventListener('change', (event) => {
const { name, value } = event.target;
options[name] = name === 'columns' ? Number(value) : value;
config.layout = layoutFor(options.columns); // changed in place: the build sees it
config.footnotes = footnotes();
doc = buildDocument({ markdown }, config); // the fonts are loaded by now
showPages(doc, { title: TITLE });
});
document.getElementById('pages').before(bar);
Каждый переключатель собирает главу заново с одной изменённой опцией. One column (одна колонка) ставит сноски внизу страницы, которая здесь и есть колонка. End of chapter (конец главы) ставит их после последнего абзаца и опускает в низ колонки, которую они закрывают, под ту же линейку. Continuous (сквозная) ведёт номера от пролога в первую главу, а не начинает заново с 1.
Рецепт целиком
// ═══ Postext Cookbook · Nº 071 · Footnotes at the foot of the column ══════════════
// https://postext.dev/en/cookbook/novel-footnotes-column-foot
// Code: MIT · Text: Lazarillo de Tormes (1554) and Markham's 1908 translation (PD)
// Fonts: EB Garamond, Bodoni Moda, IBM Plex Sans Condensed (SIL OFL 1.1) · Needs postext ≥ 1.25.0
import { buildDocument, buildDocumentWithFonts, renderPageToCanvas } from 'https://esm.sh/postext';
import { renderToPdf, decompressWoff2 } from 'https://esm.sh/postext-pdf';
const LANG = 'en'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'novel-footnotes-column-foot';
// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: oxblood for the kickers, the folios and the notes' rule; ink on warm paper
const palette = {
ink: '#241e1a', // text: a warm near-black
oxblood: '#7d2b1f', // the one accent
muted: '#6f655b', // running heads, colophon
rule: '#c9bdae', // hairlines
paper: '#fbf8f2',
};
// col(id): a colour linked to its palette entry, with the entry's hex beside the id.
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, never the default blue.
{ id: 'main-color', name: 'accent (defaults)', value: { hex: palette.oxblood, model: 'hex' } },
];
// #endregion
const TRIM = { width: 210, height: 280 }; // a school edition: two 82 mm columns
const MARGIN = { top: 23, bottom: 22, inner: 21, outer: 17 }; // mirrored
const MEASURE = TRIM.width - MARGIN.inner - MARGIN.outer; // 172 mm
const LEAD = 13.5; // body leading in pt: the baseline grid
const at = (to, edge, x = 0, y = 0) => ({ anchor: { to, edge }, offset: { x: mm(x), y: mm(y) } });
const label = { fontFamily: 'IBM Plex Sans Condensed', fontWeight: 600,
textTransform: 'uppercase' };
// The switches under the title change these and build again (#region live).
const options = { columns: 2, placement: 'column', numbering: 'chapter' };
const layoutFor = (columns) => (columns === 2
? { layoutType: 'double', gutterWidth: mm(7) } : { layoutType: 'single' });
// #region answer: the notes at the foot of the column that cites them
// In the Markdown: `Tejares,[^9]` cites a note (the id may be a word: `[^tejares]`), and
// a paragraph that opens with `[^9]:` anywhere in the chapter defines it. The engine
// numbers the notes in order of citation and keeps each note in the column of the line
// that cites it: a line whose note does not fit under it moves on with the note.
const footnotes = () => ({
placement: options.placement, // 'column' (the foot of the citing column) or 'chapterEnd'
numbering: options.numbering, // 'chapter': 1, 2, 3… again under every chapter heading
/* The option bar over the pages: three pairs of choices, each a segmented switch. */
#options {
display: flex; flex-wrap: wrap; justify-content: center; gap: 10px 18px;
max-width: 1120px; margin: 0 auto; padding: 18px 16px 6px;
font: 600 12px/1.2 "IBM Plex Sans Condensed", system-ui, sans-serif;
letter-spacing: .06em; text-transform: uppercase;
}
#options fieldset {
display: flex; margin: 0; padding: 2px; border: 1px solid #4a433d; border-radius: 999px;
}
#options label {
display: block; padding: 7px 14px; border-radius: 999px; color: #c9bdae; cursor: pointer;
}
#options input { position: absolute; opacity: 0; pointer-events: none; }
#options label:has(input:checked) { background: #7d2b1f; color: #fbf8f2; }
#options label:has(input:focus-visible) { outline: 2px solid #c9bdae; outline-offset: 2px; }
Собранный script.js работает как есть: вставьте его в модульный скрипт любой страницы или откройте рецепт на CodePen. Папка рецепта на GitHub ↗ (открывается в новой вкладке)
Варианты
#Держите сноски главы под текстом
С placement: 'chapterEnd' сноски по умолчанию стоят внизу последней колонки; chapterEndAlign: 'text' ставит их сразу под последним абзацем.
placement: options.placement,
+ chapterEndAlign: 'text',#Уберите линейку
Без линейки сноски по-прежнему отстоят от текста на spaceAbove и spaceBelowRule.
- separator: { width: 0.25, lineWidth: pt(0.5), color: col('oxblood') },
+ separator: { enabled: false },Частые ошибки
Подводный камень
Начальная полоса резервирует высоту до самого нижнего элемента, привязанного к странице
Начальная полоса с расширенным оформлением резервирует высоту своего самого нижнего элемента, причём элементы под заголовком, привязанные к странице или вылету, тоже считаются: декор внизу страницы выталкивает текст на следующую. Дайте такому элементу reserve: false (начиная с postext 1.5): он рисуется на месте привязки и ничего не резервирует. Элементы, которые следуют за самой областью заголовка (привязаны к её низу или имеют высоту 'fill'), её высоту не определяют. Оформленные начальные полосы →
Предупреждение вёрстки · undefinedFootnote
Сноска без определения
Причина. Метка [^id] ссылается на примечание, которое не определяет ни один абзац [^id]:, поэтому номер печатается над пустой сноской.
Решение. Добавьте абзац [^id]: с примечанием или исправьте id метки. Документация →
Предупреждение вёрстки · unusedFootnote
Сноска без ссылки
Причина. У определения [^id]: нет метки в тексте, поэтому примечание не набирается.
Решение. Поставьте [^id] там, где она нужна, или удалите определение. Документация →
- Знак сноски в подписи, ячейке таблицы или заголовке печатается как записан: сноски читаются в абзацах, пунктах списков, цитатах и врезках.
- Сноска никогда не делится между колонками: та, что выше своей колонки, выходит за низ. Держите сноски в несколько строк, как делают редакторы.
Источники и лицензии
- Рецепт
- Ignacio Ferro
- Текст
- La vida de Lazarillo de Tormes, Burgos edition of 1554: the prologue and the beginning of the first treatise · Anonymous · общественное достояние
- The Life of Lazarillo de Tormes, translated by Clements Markham (1908), with his notes: the prologue and the first chapter, abridged · Clements Markham · общественное достояние
- The Spanish notes, adapted from Markham's and written for this edition · Ignacio Ferro · CC BY 4.0
- Шрифты
- EB Garamond (SIL OFL 1.1) · Bodoni Moda (SIL OFL 1.1) · IBM Plex Sans Condensed (SIL OFL 1.1)
Изменить описание рецепта ↗ (открывается в новой вкладке)Папка рецепта на GitHub ↗ (открывается в новой вкладке)


