Коротко
Если колонка заканчивается на строку выше низа страницы, потому что абзац там делить нельзя, эта настройка заново разбивает один её абзац, и колонка доходит до низа.
Что получится
Три страницы журнала о побережье Littoral: большая статья о линзе Френеля, которую открывает картина с горящей линзой в фонаре маяка. Текст идёт в две флаговые колонки Public Sans с пустой строкой сетки между абзацами, а правила висячих строк (widow и orphan) держат не меньше двух строк абзаца по обе стороны разрыва. Пен верстает статью дважды. Без настройки на начальной полосе левая колонка заканчивается на строку выше правой: следующий абзац не может начаться одной строкой внизу. С ней на той же полосе первый абзац занимает на строку больше, и обе колонки заканчиваются на последней линии сетки. На обороте настройка заодно снимает лишний воздух, который выравнивание колонок добавило над двумя подзаголовками.
Рецепт отвечает на вопросы
- Почему колонка кончается на строку-две выше низа и как её заполнить, не нарушая правил висячих строк (widow, orphan)?
- Как выровнять низ колонок и последнюю страницу (вертикальная выключка)?
- Как избежать висячих строк вверху и внизу (widows, orphans) и концевых строк из одного слова (runts) и не отрывать заголовок от текста?
Короткий ответ
const balancing = {
// A ragged column has no lever of its own when the widow and orphan rules hold its last
// line back: no heading or list end to open, no justified paragraph to set looser. This
// one lets a paragraph of the short column run a line long, within its own word spacing
// (or a justified one no looser than maxWordSpacing), or, when none can, set one a line
// short so the split after it takes the line. A change is kept only when the pages end
// with fewer short columns; otherwise the column stays as it was.
fillShortColumns: true, // default false
// The paragraphs go first: a crosshead keeps its one line of air unless they cannot help.
maxLinesBeforeLoose: 0,
};
const bodyText = {
fontFamily: 'Public Sans', fontSize: pt(9.4), lineHeight: pt(LEAD), color: col('ink'),
boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
textAlign: 'left', firstLineIndent: pt(0), paragraphSpacing: true, // a grid line between
hyphenation: { enabled: true }, optimalLineBreaking: true, optimalRagged: true,
avoidWidows: true, widowMinLines: 2, avoidOrphans: true, orphanMinLines: 2, // the cause
avoidRunts: true,
};
Ингредиенты
- Возможности
- Заполнение коротких колонокВыравнивание колонокВисячие и короткие концевые строкиОптимальное разбиение на строки (Кнут — Пласс)Оформленные начальные полосыИллюстрации в дизайне страницыАтрибуты заголовковКолонтитулы и колонцифрыКолонтитулы по роли страницыСемантическая палитраСтили абзацев
- Также применяет
- Шапка главы на всю ширинуРисунки и таблицы как ресурсы
- Шрифты
- Public Sans, Libre Caslon Display, Libre Caslon Text (SIL OFL 1.1)
- Материалы
lens-1400.jpg- A lit Fresnel lens in a lighthouse lantern at dusk (Generated With Diffusion Models, оригинал)
Порядок работы
#1 · Дайте флаговой колонке собственный рычаг
const balancing = {
// A ragged column has no lever of its own when the widow and orphan rules hold its last
// line back: no heading or list end to open, no justified paragraph to set looser. This
// one lets a paragraph of the short column run a line long, within its own word spacing
// (or a justified one no looser than maxWordSpacing), or, when none can, set one a line
// short so the split after it takes the line. A change is kept only when the pages end
// with fewer short columns; otherwise the column stays as it was.
fillShortColumns: true, // default false
// The paragraphs go first: a crosshead keeps its one line of air unless they cannot help.
maxLinesBeforeLoose: 0,
};
const bodyText = {
fontFamily: 'Public Sans', fontSize: pt(9.4), lineHeight: pt(LEAD), color: col('ink'),
boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
textAlign: 'left', firstLineIndent: pt(0), paragraphSpacing: true, // a grid line between
hyphenation: { enabled: true }, optimalLineBreaking: true, optimalRagged: true,
avoidWidows: true, widowMinLines: 2, avoidOrphans: true, orphanMinLines: 2, // the cause
avoidRunts: true,
};
Выравнивание заполняет короткую колонку строками сетки над заголовком, после списка, под врезкой или рисунком и в крайнем случае набирает абзац с выключкой по формату на строку свободнее. Во флаговой колонке сплошного текста между подзаголовками ничего этого нет, и строка, которую придержали правила висячих строк, остаётся пустой. fillShortColumns позволяет флаговому абзацу колонки занять на строку больше в пределах его межсловных пробелов; если ни один абзац этого не может, он набирает один на строку короче, и абзац после разрыва поднимается и заполняет строку. Движок сохраняет изменение, только когда коротких колонок становится меньше, поэтому включённая настройка никогда не портит страницу. maxLinesBeforeLoose: 0 пробует абзацы раньше заголовков, и над каждым подзаголовком остаётся одна строка сетки.
#2 · Сверстайте статью дважды и сравните
const withFill = (fill) => ({ ...config, headings: { ...config.headings,
balancing: { ...balancing, fillShortColumns: fill } } }); // a copy: config keeps true
const build = (fill) => buildDocumentWithFonts({ markdown, resources }, withFill(fill),
kitFonts(FONTS));
const docs = { off: await build(false), on: await build(true) };
Оба документа собраны из одной конфигурации и одной строки Markdown. Вторая сборка передаёт конфигурацию как есть, первая — копию с выключенной настройкой, поэтому в пакете, который открывается в Sandbox, fillShortColumns: true. Две кнопки над столом переключают сборки. До низа заполняются только страницы, которые продолжаются дальше: страница 3 закрывает статью, и её колонки обрезаны вровень друг с другом, в обеих сборках одинаково.
#3 · Откройте статью картиной
const DEPTH = 150; // mm: how far down the page the painting bleeds
const sans = { fontFamily: 'Public Sans', fontWeight: 700, textTransform: 'uppercase' };
const at = (to, edge, x, y, width) => ({ anchor: { to, edge },
offset: { x: mm(x), y: mm(y) }, ...(width && { size: { width: mm(width) } }) });
const air = { padding: { bottom: mm(6) } }; // counts: the text starts 6 mm under the byline
const opener = {
enabled: true,
slot: { elements: [
{ kind: 'image', id: 'art', resourceId: 'lens', placement: { anchor: { to: 'bleed',
edge: 'top-left' }, size: { width: 'fill', height: mm(DEPTH) } } },
{ kind: 'text', id: 'credit', content: '{attr.credit}', ...sans, fontWeight: 500,
fontSize: pt(6.5), letterSpacing: pt(0.6), color: col('muted'), align: 'right',
placement: at('container', 'top-right', 0, DEPTH - TOP + 2) },
{ kind: 'text', id: 'kicker', content: '{attr.kicker}', ...sans, fontSize: pt(8.5),
letterSpacing: pt(1.7), color: col('brass'), align: 'left',
placement: at('container', 'top-left', 0, DEPTH - TOP + 9) },
{ kind: 'text', id: 'headline', content: '{titleText}', fontFamily: 'Libre Caslon Display',
fontSize: pt(46), lineHeight: 1.02, color: col('ink'), align: 'left',
placement: at('#kicker', 'below', 0, 2.5, 112) },
{ kind: 'text', id: 'standfirst', content: '{attr.standfirst}', fontFamily: 'Libre Caslon Text',
italic: true, fontSize: pt(12), lineHeight: 1.3, color: col('sea'), align: 'left',
placement: at('#headline', 'right-of', 8, 2.5) },
{ kind: 'text', id: 'byline', content: '{attr.byline}', ...sans, fontSize: pt(7.5),
letterSpacing: pt(1.3), color: col('ink'), align: 'left', box: air,
placement: at('#standfirst', 'below', 0, 3.5) },
] },
};
Картина — элемент изображения, привязанный к вылету, высотой 150 мм, поэтому она доходит до обреза с трёх сторон, чего не делает ни один плавающий объект. Надзаголовок, заголовок, лид и авторство берутся из атрибутов строки #. Строка автора заканчивается внутренним отступом 6 мм, который входит в высоту начала, поэтому колонки начинаются на первой линии сетки под ней.
#4 · Уберите колонтитулы с начальной полосы
const label = { ...sans, fontWeight: 600, fontSize: pt(7.5), letterSpacing: pt(1.3),
color: col('muted') };
const folio = { fontFamily: 'Public Sans', fontWeight: 700, fontSize: pt(8.5), color: col('ink') };
const pin = (edge, x, y) => ({ anchor: { to: 'page', edge }, offset: { x: mm(x), y: mm(y) } });
const sides = [['even', 'left', 1], ['odd', 'right', -1]]; // 1: the outer edge is on the left
const header = { elements: sides.flatMap(([parity, edge, s]) => [
{ kind: 'text', id: `folio-${parity}`, content: '{pageNumber}', ...folio,
placement: pin(`top-${edge}`, s * OUTER, 12) },
{ kind: 'text', id: `head-${parity}`, ...label,
content: s > 0 ? '{title} · {subtitle}' : '{chapterTitle}',
placement: pin(`top-${edge}`, s * (OUTER + 9), 12.35) }, // the smaller size's baseline
{ kind: 'rule', id: `rule-${parity}`, direction: 'horizontal', thickness: pt(0.5),
color: col('rule'), placement: { ...pin(`top-${edge}`, s * OUTER, 17),
size: { width: mm(197) } } },
].map((element) => ({ ...element, parity, pages: 'body' }))) }; // none on the opener
const footer = { elements: sides.map(([parity, edge, s]) => ({ kind: 'text', parity,
id: `drop-folio-${parity}`, ...folio, content: '{pageNumber}', pages: 'opener', align: edge,
placement: pin(`bottom-${edge}`, s * OUTER, -11) })) }; // the opener's only folio
Левая полоса называет журнал и номер из метаданных, правая — статью, а pages: 'body' убирает обе надписи с начальной полосы, где остаётся только колонцифра внизу. Надпись стоит на 0,35 мм ниже колонцифры, поэтому у двух кеглей общая базовая линия. Волосная линейка под ними длиной 197 мм, в ширину полосы набора.
Рецепт целиком
// ═══ Postext Cookbook · Nº 177 · Filling the column the widow rule left short ═════
// https://postext.dev/en/cookbook/filling-short-columns
// Code: MIT · Text: original (CC BY 4.0) · Painting: diffusion model
// Fonts: Public Sans, Libre Caslon Display, Libre Caslon Text (OFL) · Needs postext ≥ 1.65.0
//
// A magazine long read in two ragged columns, set twice. Without fillShortColumns a column
// whose paragraph would split into a widow ends a line above the foot; with it, a paragraph
// of that column is set a line longer or shorter, and the column ends on the last grid line.
import {
buildDocumentWithFonts, renderPageToCanvas, registerResourceImage,
} from 'https://esm.sh/postext';
const LANG = 'en'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'filling-short-columns';
// ─── 1 · Design ─────────────────────────────────────────────────────────────
// Every colour below is linked to this palette by id.
const palette = {
ink: '#1b2026', // text: a slate near-black
brass: '#875a14', // the accent: kicker and crossheads (6:1 on paper)
sea: '#2c4a5e', // the standfirst
rule: '#c9ccd0', // hairlines
muted: '#5d656e', // running heads, credit, colophon
paper: '#ffffff',
};
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: 'brass (defaults)', value: { hex: palette.brass, model: 'hex' } },
];
const TOP = 22; // top margin in mm: the opener's container starts here
const OUTER = 14; // outer margin in mm: folios and running heads align to it
const LEAD = 13.2; // body leading in pt: the baseline grid every column ends on
// #region answer: ragged columns that end on the grid: fillShortColumns
const balancing = {
// A ragged column has no lever of its own when the widow and orphan rules hold its last
// line back: no heading or list end to open, no justified paragraph to set looser. This
// one lets a paragraph of the short column run a line long, within its own word spacing
// (or a justified one no looser than maxWordSpacing), or, when none can, set one a line
// short so the split after it takes the line. A change is kept only when the pages end
// with fewer short columns; otherwise the column stays as it was.
fillShortColumns: true, // default false
// The paragraphs go first: a crosshead keeps its one line of air unless they cannot help.
maxLinesBeforeLoose: 0,
};
const bodyText = {
Собранный script.js работает как есть: вставьте его в модульный скрипт любой страницы или откройте рецепт на CodePen. Папка рецепта на GitHub ↗ (открывается в новой вкладке)
Варианты
#Пусть сначала раздвинутся подзаголовки
При порядке по умолчанию заголовок берёт до двух строк сетки, прежде чем абзац станет длиннее, и подзаголовки на обороте снова раздвигаются.
- maxLinesBeforeLoose: 0,
+ maxLinesBeforeLoose: 2,#Выключите текст по формату
Абзац с выключкой по формату и без настройки может стать на строку свободнее, в пределах maxWordSpacing. С fillShortColumns он может стать и на строку плотнее, но никогда не свободнее своей самой разреженной строки.
- textAlign: 'left', firstLineIndent: pt(0), paragraphSpacing: true, // a grid line between
+ textAlign: 'justify', firstLineIndent: pt(0), paragraphSpacing: true, // a grid line betweenЧастые ошибки
- Настройка закрывает пустоту в одну строку. Колонка короче на две, например та, что заканчивается отбивкой абзаца и местом лишь для одной строки следующего, может остаться короткой: подгоните текст на одно предложение.
- Абзац, который в новом наборе закончился бы короткой концевой строкой, не используется, поэтому колонка может остаться короткой, если в ней только короткие абзацы.
Источники и лицензии
- Рецепт
- Ignacio Ferro
- Текст
- Оригинальный текст, CC BY 4.0
- Изображения
- A lit Fresnel lens in a lighthouse lantern at dusk · Generated With Diffusion Models · оригинал
- Шрифты
- Public Sans (SIL OFL 1.1) · Libre Caslon Display (SIL OFL 1.1) · Libre Caslon Text (SIL OFL 1.1)
Изменить описание рецепта ↗ (открывается в новой вкладке)Папка рецепта на GitHub ↗ (открывается в новой вкладке)


