Em poucas palavras
Um livro curto sobre os jeitos de começar um capítulo, em que cada capítulo abre num estilo diferente. Mostra como dar a um capítulo cores, margens e diagramação próprias com um único ajuste.
O que você vai compor
Five Ways to Begin é um livro de sete páginas sobre aberturas de capítulo, em 180 × 240 mm, e cada capítulo é composto com a abertura que descreve. O primeiro é de romance: um chapéu espacejado, um título em itálico leve e uma capitular vermelha de cinco linhas, com cabeços nas páginas seguintes. O segundo põe o título e um florão dentro de uma cartela creme desenhada com dois fios azuis. O terceiro empilha o título em Fraunces Black branca sobre um campo magenta que sangra para fora da página, acima de uma inicial monoespaçada vazada numa caixa. O quarto, o do manual, tem cabeços em monoespaçada, um selo laranja com o número ao lado do título e duas colunas de Geist. A coda põe o título no meio de uma página vazia, sobre uma inicial elevada. O capítulo um usa a abertura do próprio nível 1; os outros quatro indicam um estilo de título na linha do título.
Esta receita responde a
- Como dou a cada capítulo sua própria foto, cor ou variante de abertura?
- Como acrescento a uma abertura uma linha de autor, uma linha fina ou um primeiro parágrafo com capitular?
- Como coloco o título do capítulo na largura da página enquanto o texto segue em duas colunas abaixo?
- Como faço um selo com o número ao lado do título que se alarga quando o número cresce (9 → 10)?
A resposta curta
// 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()
Ingredientes
- Funcionalidades
- Estilos de títuloGeometria por seçãoCapitulares em parágrafos do textoCabeços por seçãoAberturas desenhadasCores por parteCapítulos sem númeroFaixa de capítulo em largura totalTextos, fios e caixas nos designs de páginaImagens nos designs de páginaAtributos de títuloFaixas sangradas e guias lateraisQuebras de linha nos títulosAncoragem de elementos de designCabeços e fóliosCabeços por tipo de páginaPaleta de cores semânticaTítulos numeradosEstilos de parágrafoFiguras e tabelas como recursos
- Também usa
- Espaço vertical explícito
- Tipografia
- Lora, Fraunces, Geist, Geist Mono (SIL OFL 1.1)
- Materiais
- Nenhum: todas as imagens são desenhadas em código
Preparo
#1 · Ponha no nível a abertura própria do livro
// 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),
]);
O capítulo um não tem estilo, por isso recebe o design do nível 1, do qual todo estilo parte (a resposta curta mostra o nível e os estilos). O primeiro parágrafo do capítulo está no Markdown, num grupo :::paragraphs{style="lead"} um corpo acima do texto (12/17 pt contra 10,8/14,5), e o dropCap do nível o abre (capitulares): o M se apoia na quinta linha de base e, sem fontSize, o alto fica na altura das maiúsculas da primeira linha, com as duas alturas de maiúsculas medidas na Fraunces e na Lora. A abertura termina com uma caixa vazia, room(), 17 mm abaixo do título, onde começa o parágrafo de abertura; um :::space sob o parágrafo de abertura deixa uma linha e faz o texto começar sem recuo.
#2 · Emoldure o título com duas caixas
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
]);
A ordem do array é a ordem de pintura, por isso as caixas vêm primeiro e o texto por cima; o florão é um elemento de imagem, que desenha um recurso SVG registrado que nunca é numerado nem citado. Um elemento de imagem também é o jeito de dar a cada capítulo uma foto própria: desde o postext 1.8 seu resourceId aceita marcadores, de modo que com resourceId: '{attr.photo}' um mesmo estilo desenha a foto que cada título indica, # The Frame {style="framed" photo="lake"}, como fazem os pratos da ficha de receita (elementos de imagem). O estilo framed da resposta curta usa palette para deixar accent azul nas páginas deste capítulo, de modo que os fios, o chapéu e o fólio do pé saem em azul, e suas margins centralizam a mancha sob a moldura. O dropCap do próprio estilo usa col('accent'), que a paleta também deixa azul, e assim o L de três linhas combina com a moldura.
#3 · Empilhe o título e ponha a inicial numa caixa
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
]);
A pilha se escreve no Markdown: # Say it \\ out \\ loud. quebra {titleText} em cada \\, enquanto os cabeços e os marcadores do PDF leem o título numa linha só (quebras de linha em títulos). O campo pende do alto da sangria, na largura inteira e com 130 mm de altura, e o parágrafo de abertura começa na primeira linha da grade, 8 mm abaixo dele (TEXT_TOP). A inicial em caixa são duas peças. O dropCap do estilo compõe o M em branco ao longo de três linhas do parágrafo de abertura, e a abertura pinta embaixo dele uma caixa magenta, posicionada a partir de TEXT_TOP, da entrelinha do parágrafo e das métricas da Geist Mono, de modo que a cor acima e abaixo do M tem a largura do espaço lateral. A caixa não ocupa espaço na abertura (reserve: false); uma caixa room vazia termina a abertura onde começa o parágrafo de abertura.
#4 · Dê ao manual um selo, duas colunas e cabeços próprios
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),
];
};
O selo é um elemento de texto com preenchimento e espaçamento interno, mas sem largura, por isso a largura acompanha {chapterNumber}, e o título é posicionado right-of ele: no capítulo 10 o selo cresce um algarismo, 5,5 mm, e o título anda junto. O espaçamento inferior é 1 mm menor que o superior porque a caixa de linha guarda esse milímetro a mais embaixo dos algarismos, e assim o 4 fica centralizado. No estilo spec, layout põe a seção em duas colunas e o span: 'page' do nível estende a abertura sobre as duas. Suas margins alargam a mancha para 144 mm, bodyStyle compõe Geist em bandeira sobre a grade de 14,5 pt do livro, header substitui os cabeços do livro e um footer vazio tira o fólio.
#5 · Deixe espaço para a coda
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')] };
O chapéu pende 92 mm abaixo do alto da mancha, e a inicial elevada é a capitular de uma linha do estilo quiet: o pé dela se apoia na primeira linha de base e, com 46 pt, ela sobe para o branco de cima em vez de afundar no parágrafo. O parágrafo mantém essa subida livre acima dele em linhas inteiras, por isso o room da abertura sob o título tem só 3 mm. No estilo quiet, margins estreitam a medida para 106 mm, bodyStyle compõe o texto em bandeira a 12,5/17,5 pt, footer troca o fólio do pé por um pequeno no canto externo e palette deixa o chapéu cinza. Nada nesta página imprime número de capítulo, por isso numbered: false só apareceria num capítulo acrescentado depois da coda, que continuaria sendo o quinto.
A receita completa
// ═══ 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:
O script.js montado funciona como está: cole-o como script de módulo em qualquer página ou abra a receita no CodePen. Pasta da receita no GitHub ↗ (abre em uma nova aba)
Variações
#Mande cada capítulo para uma página ímpar
Com 'odd', todo capítulo abre numa página da direita e os capítulos dois a cinco ganham cada um uma página par em branco antes, de modo que o livro passa de 7 para 11 páginas.
- breakBefore: { enabled: true, parity: 'any' },
+ breakBefore: { enabled: true, parity: 'odd' },#Deixe a capitular em três linhas
Sem fontSize, o tamanho acompanha o número de linhas, por isso uma capitular de três linhas também se alinha com as maiúsculas da primeira linha.
- dropCap: { lines: 5, fontFamily: 'Fraunces', fontWeight: 400, color: col('accent'),
+ dropCap: { lines: 3, fontFamily: 'Fraunces', fontWeight: 400, color: col('accent'),#Versaletes depois da inicial
leadIn compõe em versaletes as primeiras palavras depois da letra, como fazem muitos romances; words: 'line' pega a primeira linha inteira.
- gap: mm(2.5) } });
+ gap: mm(2.5), leadIn: { words: 'line' } } });Erros comuns
Erro comum
Valores de atributo: sem { ou }; aspas simples se tiver "
Um valor de atributo termina na chave de fechamento, por isso não pode conter { nem }. Um valor que contém aspas duplas vai entre aspas simples; o cifrão não causa problema. Atributos de título →
- Os parágrafos de abertura são compostos em bandeira, como numa abertura de revista; um parágrafo de abertura justificado ao lado de uma inicial de cinco linhas pode abrir muito os espaços numa linha de poucas palavras.
- A caixa magenta está ajustada à mão para Lora 12/17, para o M da Geist Mono e para a linha de base da linha, a 0,8 da caixa de linha (
BASE). Se você mudar a fonte, o tamanho ou a entrelinha do parágrafo de abertura, a letra, o número de linhas ou a altura do campo, confira de novo a caixa contra as maiúsculas da primeira linha. - Títulos nunca giram nem correm na vertical: o texto de design é sempre horizontal. Empilhe as palavras com
\\, como faz o capítulo três.
Créditos
- Receita
- Ignacio Ferro
- Texto
- Texto original, CC BY 4.0
- Fontes
- Lora (SIL OFL 1.1) · Fraunces (SIL OFL 1.1) · Geist (SIL OFL 1.1) · Geist Mono (SIL OFL 1.1)
- Código
- MIT, como o Postext
Editar este texto ↗ (abre em uma nova aba)Pasta da receita no GitHub ↗ (abre em uma nova aba)


