Перейти к основному содержанию
Рецепт номер 17

Рецепты · Глава 3 · Заголовки и начальные полосы

Пять начал главы в одной книге

Одно начало на уровне 1 и четыре стиля заголовков, названные в Markdown; каждый меняет акцентный цвет, а некоторые — поля, колонки или колонцифры.

На этой странице
Вывод
Canvas
Postext
Проверено с Postext 1.65.0
Требуется ≥ 1.25.0
Лицензия
Обновлено 10 окт. 2026 г.
Код: MIT · Текст: CC BY 4.0

с. 4–5 из 7

  • Образец на английском: русского издания пока нет
  • Обрезной формат 180 × 240 мм
  • 1 колонка
  • Lora 10,8/14,5
  • Fraunces
  • Geist
  • Geist Mono
  • 7 страниц
  • Уровень
  • Postext 1.57.1
  • Свёрстано за 72 мс
  • Строк кода: 249

Коротко

Небольшая книга о том, как может начинаться глава: каждая глава в ней начинается по-своему. Показано, как одной настройкой дать главе свои цвета, поля и вёрстку.

Что получится

Five Ways to Begin — книга на семь страниц о начале главы, 180 × 240 мм, и каждая глава набрана с тем началом, которое описывает. Первая глава — романная: надзаголовок с трекингом, светлый курсивный заголовок и красная буквица в пять строк, на следующих страницах колонтитулы. Вторая помещает заголовок и типографский цветок в кремовый картуш из двух синих линеек. Третья ставит заголовок столбиком, белым Fraunces Black на пурпурном поле под обрез, над моноширинной буквицей вывороткой в прямоугольнике. У четвёртой, руководства, моноширинные колонтитулы, оранжевый номерной знак у заголовка и две колонки Geist. Кода ставит заголовок на середину пустой страницы, над приподнятой буквицей. Первая глава использует собственное начало уровня 1; остальные четыре называют стиль заголовка в своей строке заголовка.

Рецепт отвечает на вопросы

  • Как дать каждой главе своё фото, цвет или вариант начальной полосы?
  • Как добавить на начальную полосу строку с автором, вводку или лид с буквицей?
  • Как набрать название главы во всю ширину, а текст под ним — в две колонки?
  • Как сделать рядом с названием плашку с номером, которая расширяется вместе с ним (9 → 10)?

Короткий ответ

script.js · строки 16–52в полном коде
// A heading line picks a style by id, and its attributes feed the opener's {attr.…} texts:
//   # The Frame {style="framed" kicker="Chapter the Second"}
// A style overrides the level fields it names (opener, drop cap) and, until the next level-1
// heading, the section fields it names; the rest comes from the level and the document.
const level1 = () => ({ level: 1,
  // span 'page' opens each chapter at the head of a new page and runs its opener across
  // every column (chapter four has two). By default an H1 waits for a recto, with a blank
  // page before it; parity 'any' lets these short chapters open on either side.
  span: 'page',
  breakBefore: { enabled: true, parity: 'any' },
  marginBottom: pt(0), // each opener ends where its first paragraph starts
  advancedDesign: literary, // chapter one, unstyled: the book's own opener
  dropCap: { lines: 5, fontFamily: 'Fraunces', fontWeight: 400, color: col('accent'),
    gap: mm(2.5) } }); // a five-line drop in rubric red
const headingStyles = () => [ // factories, called by config() once every design exists
  // Each style brings its opener and swaps 'accent' for a colour of its own, on its pages.
  { id: 'framed', advancedDesign: framed, palette: { accent: palette.lapis },
    margins: { left: mm(EVEN), right: mm(EVEN) }, // a centred text block; 'accent' is blue:
    dropCap: { lines: 3, fontFamily: 'Fraunces', fontWeight: 600, color: col('accent'),
      gap: mm(2) } },
  { id: 'stacked', advancedDesign: stacked, palette: { accent: palette.magenta }, // white, on
    dropCap: { lines: BOXED, fontFamily: 'Geist Mono', fontWeight: 700, color: col('paper'),
      gap: mm(2.2) } }, // the square the opener draws for it
  { id: 'spec', advancedDesign: spec, palette: { accent: palette.signal }, dropCap: false,
    marginBottom: pt(0), // the hairline under the title is the separator
    margins: { left: mm(SPEC), right: mm(SPEC) }, // a 144 mm text block
    layout: { layoutType: 'double', gutterWidth: mm(7) },
    bodyStyle: { fontFamily: 'Geist', fontSize: pt(9.8), textAlign: 'left' }, // on the grid
    header: { elements: [...specHead('even'), ...specHead('odd')] },
    footer: { elements: [] } }, // no folio at the foot: the head gives the page
  { id: 'quiet', numbered: false, // a coda: it advances no chapter counter
    advancedDesign: quiet, palette: { accent: palette.graphite }, footer: tinyFolio,
    dropCap: { lines: 1, fontFamily: 'Fraunces', fontWeight: 300, fontSize: pt(46), // raised:
      color: col('accent'), gap: mm(1.2) }, // on the first baseline, rising into the white
    margins: { left: mm(QUIET.inner), right: mm(QUIET.outer) }, // a 106 mm measure
    bodyStyle: { fontSize: pt(QUIET.size), lineHeight: pt(QUIET.lead), textAlign: 'left' } },
]; // hook-up in config(): headings: { levels: [level1(), …] }, headingStyles()

Ингредиенты

Возможности
Стили заголовковГеометрия разделаБуквицы в абзацах текстаКолонтитулы разделовОформленные начальные полосыЦвета частейГлавы без номераШапка главы на всю ширинуТекст, линейки и рамки в дизайне страницыИллюстрации в дизайне страницыАтрибуты заголовковЦветные поля навылет и метки на обрезеРазрывы строк в заголовкахПривязка элементов дизайнаКолонтитулы и колонцифрыКолонтитулы по роли страницыСемантическая палитраНумерованные заголовкиСтили абзацевРисунки и таблицы как ресурсы
Шрифты
Lora, Fraunces, Geist, Geist Mono (SIL OFL 1.1)
Материалы
Нет: все иллюстрации рисует код

Порядок работы

#1 · Задайте начало книги на уровне заголовка

script.js · строки 97–105в полном коде
// The first paragraph, in :::paragraphs{style="lead"}, starts 17 mm under the title.
const literary = design([
  text('kicker', '{attr.kicker}', 'Geist', 8, centred(22), { ...caps(1.7), align: 'center' }),
  text('title', '{titleText}', 'Fraunces', 32, at('#kicker', 'below', 0, 4, 'fill'),
    { fontWeight: 300, italic: true, lineHeight: 1.05, align: 'center' }),
  { kind: 'rule', id: 'rule', direction: 'horizontal', thickness: pt(0.8), color: col('accent'),
    placement: at('#title', 'below', (MEASURE - 18) / 2, 6, 18) }, // an 18 mm rule, centred
  room('#title', 17),
]);

У первой главы нет стиля, поэтому она берёт оформление самого уровня 1, от которого отталкивается каждый стиль (короткий ответ показывает уровень и стили). Первый абзац главы стоит в Markdown в группе :::paragraphs{style="lead"}, на кегль крупнее текста (12/17 пт против 10,8/14,5), и его открывает dropCap уровня (буквицы): M стоит на пятой базовой линии, а без fontSize её верх выровнен по прописным первой строки, высота которых измерена по Fraunces и Lora. Оформление кончается пустым блоком room(), на 17 мм ниже заголовка, где начинается вступление; :::space под вступлением оставляет строку и начинает текст без отступа.

#2 · Обрамите заголовок двумя блоками

script.js · строки 109–127в полном коде
const FRAME = 62; // mm: the outer box's height
const INSET = 3; // mm: the hairline box runs this far inside it
const FLEURON = 44; // mm: the ornament's width, centred under the title
const framed = design([ // array order is paint order: the boxes first, the type on top
  { kind: 'box', id: 'frame', placement: { ...at('container', 'top-left', 0, 0),
    size: { width: 'fill', height: mm(FRAME) } },
  style: { backgroundColor: col('tint'), borderColor: col('accent'), borderWidth: pt(1.6) } },
  { kind: 'box', id: 'hairline', placement: { ...at('#frame', 'align-top', INSET, INSET),
    size: { width: mm(MEASURE - 2 * INSET), height: mm(FRAME - 2 * INSET) } },
  style: { borderColor: col('accent'), borderWidth: pt(0.5) } },
  text('kicker', '{attr.kicker}', 'Geist', 7.5, centred(14), { ...caps(1.6), align: 'center' }),
  text('title', '{titleText}', 'Fraunces', 34, at('#kicker', 'below', 0, 3.5, 'fill'),
    { fontWeight: 600, lineHeight: 1.05, align: 'center' }),
  // An image element draws a registered resource, never numbered or captioned. Its resourceId
  // may be '{attr.photo}' (postext ≥ 1.8): then each heading names its own photo.
  { kind: 'image', id: 'fleuron', resourceId: 'fleuron',
    placement: at('#title', 'below', (MEASURE - FLEURON) / 2, 4.5, FLEURON) },
  room('#frame', 9), // the text starts 9 mm under the frame
]);

Порядок в массиве — это порядок рисования, поэтому сначала идут блоки, а текст сверху; украшение — это элемент-изображение, который рисует зарегистрированный SVG-ресурс без номера и без ссылки на него. С помощью такого элемента каждая глава получает и собственное фото: начиная с postext 1.8 его resourceId принимает подстановки, и с resourceId: '{attr.photo}' один стиль рисует фото, которое назвал каждый заголовок, # The Frame {style="framed" photo="lake"}, как блюда в рецепте карточка блюда (элементы-изображения). Стиль framed из короткого ответа через palette делает accent синим на страницах этой главы, поэтому линейки, надзаголовок и нижняя колонцифра печатаются синим, а его margins центрируют полосу набора под рамкой. Собственный dropCap стиля называет col('accent'), который палитра тоже делает синим, и L в три строки подходит к рамке.

#3 · Поставьте заголовок столбиком, буквицу — в прямоугольник

script.js · строки 131–160в полном коде
const FIELD = 130; // mm from the trim: the foot of the colour field
const S_BEARING = 1.2; // mm: the white left of the title's S (0.0365 em at 94 pt)
// The boxed initial: the style's drop cap sets the white letter; the opener draws the square,
// fitted by hand in pt. The text starts on the grid line 8 mm under the field (from the trim).
const TEXT_TOP = Math.ceil(((FIELD - TOP + 8) * 72) / 25.4 / LEAD) * LEAD; // pt
const BASE = 0.8; // a line's baseline stands 0.8 down its line box
const CAPS = 0.7; // the height of a capital in Lora, em
// Geist Mono, em: cap height, the advance every capital shares, the white either side of an M
const MONO = { caps: 0.71, advance: 0.6, side: 0.044 };
const BOXED = 3; // lines the initial spans
const capsTop = TEXT_TOP + BASE * LEADIN.lead - CAPS * LEADIN.size; // the first line's capitals
const foot = TEXT_TOP + (BOXED - 1 + BASE) * LEADIN.lead; // the third baseline: the letter's foot
// The M runs from the first line's capitals to its foot; the square runs past both as far as
// the M's sides sit in, so the colour is as wide on all four sides.
const letter = (foot - capsTop) / MONO.caps, pad = MONO.side * letter;
const stacked = design([
  { kind: 'box', id: 'field', style: { backgroundColor: col('accent') },
    placement: { anchor: { to: 'bleed', edge: 'top-left' }, size: { height: mm(FIELD) } } },
  text('kicker', '{attr.kicker}', 'Geist', 8, at('container', 'top-left', 0, 4),
    { ...caps(1.8), color: col('paper') }),
  // {titleText} keeps the \\ breaks from the Markdown, so each line ends at the writer's \\.
  // Moved left by the S's side bearing, so its curve meets the text edge.
  text('title', '{titleText}', 'Fraunces', 94,
    at('container', 'top-left', -S_BEARING, 15, 'fill'),
    { fontWeight: 900, lineHeight: 0.84, color: col('paper') }),
  { kind: 'box', id: 'initial', style: { backgroundColor: col('accent') }, reserve: false,
    placement: { anchor: { to: 'container', edge: 'top-left' }, offset: { y: pt(capsTop - pad) },
      size: { width: pt(MONO.advance * letter), height: pt(foot - capsTop + 2 * pad) } } },
  room('container', (TEXT_TOP * 25.4) / 72, 'top-left'), // the opener ends where the text starts
]);

Столбик записан в Markdown: # Say it \\ out \\ loud. разрывает {titleText} на каждом \\, а колонтитулы и оглавление PDF читают заголовок в одну строку (переносы строк в заголовках). Поле подвешено к верху вылета, во всю ширину и глубиной 130 мм, а вступление начинается с первой линии сетки на 8 мм ниже (TEXT_TOP). Буквица в прямоугольнике состоит из двух частей. dropCap стиля набирает M белым на три строки вступления, а оформление начала рисует под ней пурпурный прямоугольник по TEXT_TOP, интерлиньяжу вступления и метрикам Geist Mono, так что цвет над M и под ней равен по ширине её полуапрошам. Прямоугольник не занимает места в оформлении (reserve: false); пустой блок room завершает его там, где начинается вступление.

#4 · Дайте руководству номерной знак, две колонки и свои колонтитулы

script.js · строки 181–208в полном коде
const SPEC = 18; // mm: both side margins, for a 144 mm text block in two columns
const PAD = 1.6; // mm of colour over the badge's figures
const spec = design([
  { kind: 'rule', id: 'top-rule', direction: 'horizontal', thickness: pt(2.4), color: col('ink'),
    placement: at('container', 'top-left', 0, 0, 'fill') },
  text('kicker', '{attr.kicker}', 'Geist Mono', 7.5, at('container', 'top-left', 0, 3.2),
    { ...caps(1.2, 500), color: col('graphite') }),
  // The badge's width follows its text, with padding on both sides, so 9 → 10 widens it. Its
  // line box holds 1 mm more under the figures than over them, so the foot pads 1 mm less.
  text('badge', '{chapterNumber}', 'Geist Mono', 26, at('container', 'top-left', 0, 12),
    { fontWeight: 700, lineHeight: 1, box: { backgroundColor: col('accent'), padding: {
      top: mm(PAD), right: mm(2.4), bottom: mm(PAD - 1), left: mm(2.4) } } }),
  // Same size and line height as the badge, dropped by its top padding, so the baselines meet.
  text('title', '{titleText}', 'Geist', 26, at('#badge', 'right-of', 4, PAD),
    { fontWeight: 700, lineHeight: 1 }),
  { kind: 'rule', id: 'hairline', direction: 'horizontal', thickness: pt(0.5), color: col('ink'),
    placement: at('container', 'top-left', 0, 31, 'fill') }, // room for a one-line title
]);
const specHead = (parity) => { // mono labels over the opener's rule, on every page of the section
  const [edge, s] = parity === 'even' ? ['top-left', 1] : ['top-right', -1];
  const mono = { ...caps(1.1, 500), color: col('graphite'), parity, pages: 'all' };
  return [
    text(`sp-page-${parity}`, '{pageNumber} / {totalPages}', 'Geist Mono', 7,
      at('container', edge, 0, HEAD_Y), mono),
    text(`sp-chap-${parity}`, '§ {chapterNumber} · {chapterTitle}', 'Geist Mono', 7,
      at('container', edge, s * 16, HEAD_Y), mono),
  ];
};

Знак — это текстовый элемент с заливкой и внутренними отступами, но без ширины, поэтому его ширина зависит от {chapterNumber}, а заголовок стоит right-of него: в главе 10 знак вырастет на одну цифру, 5,5 мм, и заголовок сдвинется вместе с ним. Нижний отступ на 1 мм меньше верхнего, потому что ровно на столько больше места в строке под цифрами, и 4 стоит по центру. В стиле spec layout ставит раздел в две колонки, а span: 'page' уровня проводит начало через обе. margins расширяют полосу набора до 144 мм, bodyStyle набирает флаговым набором Geist по сетке книги 14,5 пт, header заменяет колонтитулы книги, а пустой footer убирает колонцифру.

#5 · Оставьте коде место

script.js · строки 212–221в полном коде
const quiet = design([ // the kicker is in the accent, which this style turns graphite
  text('kicker', '{attr.kicker}', 'Geist', 7.5, at('container', 'top-left', 0, 92),
    caps(1.6, 500)),
  text('title', '{titleText}', 'Fraunces', 26, at('#kicker', 'below', 0, 3),
    { fontWeight: 300, lineHeight: 1.1 }),
  room('#title', 3), // and the initial's rise, in whole lines: the text 16 mm under the title
]);
const tiny = (parity, edge) => text(`tiny-${parity}`, '{pageNumber}', 'Geist', 6.5,
  at('container', edge, 0, -12), { fontWeight: 500, color: col('muted'), parity });
const tinyFolio = { elements: [tiny('even', 'bottom-left'), tiny('odd', 'bottom-right')] };

Надзаголовок висит на 92 мм ниже верха полосы набора, а приподнятая буквица — это буквица стиля quiet в одну строку: её основание стоит на первой базовой линии, и при кегле 46 пт она поднимается в белое поле над строкой, а не уходит в абзац. Абзац освобождает над собой место для неё целыми строками, поэтому room под заголовком всего 3 мм. В стиле quiet margins сужают строку до 106 мм, bodyStyle ставит флаговый набор 12,5/17,5 пт, footer меняет нижнюю колонцифру на мелкую у внешнего угла, а palette делает надзаголовок серым. На этой странице номер главы не печатается, поэтому numbered: false проявился бы только в главе после коды: она всё равно была бы пятой.

Рецепт целиком

Sandbox
// ═══ Postext Cookbook · Nº 017 · Five chapter openers in one book ═════════════════
// https://postext.dev/en/cookbook/five-chapter-openers
// Code: MIT · Text: original (CC BY 4.0) · Ornament: generated in code (CC BY 4.0)
// Fonts: Lora, Fraunces, Geist, Geist Mono (SIL OFL 1.1) · Needs postext ≥ 1.25.0
// A small book about openers, each chapter set in the one it describes. Every heading style
// brings its opener and palette; three move the margins, two bring their own type and folios.
import {
  buildDocumentWithFonts, renderPageToCanvas, registerResourceImage,
} from 'https://esm.sh/postext';

const LANG = 'en'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'five-chapter-openers';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region answer: one opener per chapter: the level's own, then heading styles by name
// A heading line picks a style by id, and its attributes feed the opener's {attr.…} texts:
//   # The Frame {style="framed" kicker="Chapter the Second"}
// A style overrides the level fields it names (opener, drop cap) and, until the next level-1
// heading, the section fields it names; the rest comes from the level and the document.
const level1 = () => ({ level: 1,
  // span 'page' opens each chapter at the head of a new page and runs its opener across
  // every column (chapter four has two). By default an H1 waits for a recto, with a blank
  // page before it; parity 'any' lets these short chapters open on either side.
  span: 'page',
  breakBefore: { enabled: true, parity: 'any' },
  marginBottom: pt(0), // each opener ends where its first paragraph starts
  advancedDesign: literary, // chapter one, unstyled: the book's own opener
  dropCap: { lines: 5, fontFamily: 'Fraunces', fontWeight: 400, color: col('accent'),
    gap: mm(2.5) } }); // a five-line drop in rubric red
const headingStyles = () => [ // factories, called by config() once every design exists
  // Each style brings its opener and swaps 'accent' for a colour of its own, on its pages.
  { id: 'framed', advancedDesign: framed, palette: { accent: palette.lapis },
    margins: { left: mm(EVEN), right: mm(EVEN) }, // a centred text block; 'accent' is blue:
    dropCap: { lines: 3, fontFamily: 'Fraunces', fontWeight: 600, color: col('accent'),
      gap: mm(2) } },
  { id: 'stacked', advancedDesign: stacked, palette: { accent: palette.magenta }, // white, on
    dropCap: { lines: BOXED, fontFamily: 'Geist Mono', fontWeight: 700, color: col('paper'),
      gap: mm(2.2) } }, // the square the opener draws for it
  { id: 'spec', advancedDesign: spec, palette: { accent: palette.signal }, dropCap: false,
    marginBottom: pt(0), // the hairline under the title is the separator
    margins: { left: mm(SPEC), right: mm(SPEC) }, // a 144 mm text block
    layout: { layoutType: 'double', gutterWidth: mm(7) },
    bodyStyle: { fontFamily: 'Geist', fontSize: pt(9.8), textAlign: 'left' }, // on the grid
    header: { elements: [...specHead('even'), ...specHead('odd')] },
    footer: { elements: [] } }, // no folio at the foot: the head gives the page
  { id: 'quiet', numbered: false, // a coda: it advances no chapter counter
    advancedDesign: quiet, palette: { accent: palette.graphite }, footer: tinyFolio,
    dropCap: { lines: 1, fontFamily: 'Fraunces', fontWeight: 300, fontSize: pt(46), // raised:

Собранный script.js работает как есть: вставьте его в модульный скрипт любой страницы или откройте рецепт на CodePen. Папка рецепта на GitHub ↗ (открывается в новой вкладке)

Варианты

#Начинайте каждую главу с правой полосы

С 'odd' каждая глава открывается на правой странице, а перед главами со второй по пятую появляется пустая левая, и книга растёт с 7 до 11 страниц.

-  breakBefore: { enabled: true, parity: 'any' },
+  breakBefore: { enabled: true, parity: 'odd' },

#Опустите буквицу на три строки

Без fontSize кегль следует за числом строк, поэтому буквица в три строки всё равно выровнена по прописным первой строки.

-  dropCap: { lines: 5, fontFamily: 'Fraunces', fontWeight: 400, color: col('accent'),
+  dropCap: { lines: 3, fontFamily: 'Fraunces', fontWeight: 400, color: col('accent'),

#Капитель после буквицы

leadIn набирает первые слова после буквы капителью, как во многих романах; words: 'line' берёт всю первую строку.

-    gap: mm(2.5) } });
+    gap: mm(2.5), leadIn: { words: 'line' } } });

Частые ошибки

Подводный камень

Значения атрибутов: без { и }; значение с " — в одинарных кавычках

Значение атрибута заканчивается на закрывающей фигурной скобке, поэтому { и } внутри него невозможны. Значение с двойной кавычкой берётся в одинарные; знак доллара допустим. Атрибуты заголовков →

  • Вступления набраны флагом, как в журнале: при выключке по формату рядом с буквицей в пять строк пробелы в строке из немногих слов могут широко разойтись.
  • Пурпурный прямоугольник подогнан вручную под Lora 12/17, под M из Geist Mono и под базовую линию, которая проходит на 0,8 высоты строки (BASE). Если вы меняете шрифт, кегль или интерлиньяж вступления, букву, число строк или глубину поля, снова проверьте прямоугольник по прописным первой строки.
  • Заголовки не поворачиваются и не идут вертикально: текст оформления всегда горизонтален. Ставьте слова столбиком через \\, как в третьей главе.

Источники и лицензии

Рецепт
Ignacio Ferro
Текст
Оригинальный текст, CC BY 4.0
Шрифты
Lora (SIL OFL 1.1) · Fraunces (SIL OFL 1.1) · Geist (SIL OFL 1.1) · Geist Mono (SIL OFL 1.1)
Sandbox