Skip to main content

13  Themes, CSS, Templates, and Extensions

A mathematical argument should not become harder to follow because it appears on a phone rather than on paper. A reader should recognize a definition, a worked example, and a computational investigation without having to relearn the visual language in every chapter. A coherent publishing system makes these distinctions consistently while preserving the mathematical meaning of the source.

13.1 Learning objectives

After completing this chapter, you should be able to distinguish CSS from SCSS, configure a theme, design accessible instructional components, separate print and web settings, package reusable templates, and evaluate the behavior and trustworthiness of extensions.

13.2 Separate content from presentation

A chapter contains the argument, equations, code, and evidence. The configuration specifies the output formats and shared defaults. A stylesheet controls the appearance of HTML elements. A filter changes the document structure before output is produced. Keeping these responsibilities separate is more than a convenience: it allows an editor to change the appearance of hundreds of pages without rewriting the mathematics.

Consider an author who manually inserts a colored HTML box around every definition. The box might work in a browser but disappear in Word or PDF. A better strategy is to use Quarto’s semantic theorem and callout structures, which identify the role of the content before choosing how to display it. A custom class can supplement those structures when a particular visual treatment is needed.

Layer Typical file Responsibility
Content chapter.qmd Explanations, mathematics, examples
Configuration _quarto.yml Shared format options and navigation
Theme series.scss Bootstrap variables and compiled rules
Stylesheet components.css HTML component appearance
Print header print-header.tex LaTeX-specific adjustments
Filter learning-box.lua Document transformations

13.3 CSS fundamentals

A CSS rule consists of a selector and declarations. A selector identifies elements; declarations describe properties and values. For example:

.learning-box {
  border-inline-start: 0.25rem solid #26766a;
  padding: 0.8rem 1rem;
  background: #f2f8f6;
  color: #243447;
}

The leading period denotes a class selector. A class can be applied to multiple elements without requiring unique identifiers. The rem unit is relative to the root font size, which helps spacing respond to reader settings. Logical properties such as border-inline-start are preferable when a design may need to support different writing directions.

Apply the class using a fenced Div:

::: {.learning-box}
**Guided practice.** Explain the slope in context.
:::

The bold label is meaningful even when the stylesheet is absent. This is a useful test of semantic design: disable CSS and ask whether the content remains understandable.

13.3.1 Cascade and specificity

When several rules apply to an element, the browser resolves conflicts using the cascade, including origin, importance, specificity, and order. For ordinary author rules in the same layer, a class selector is more specific than an element selector; an ID selector is more specific than a class selector. Equal-specificity rules are normally resolved by source order. Avoid using !important as a routine fix: it can make later customization unnecessarily difficult.

Use browser developer tools to inspect the element and its computed styles. If a rule is crossed out, identify the winning rule rather than adding arbitrary declarations. If a selector matches no elements, inspect the generated HTML to determine whether the class actually exists.

13.4 SCSS and Quarto themes

SCSS adds variables and other conveniences to CSS. Quarto’s Bootstrap-based HTML themes can be customized through a theme file with sections for defaults and rules. The following example establishes a restrained academic palette.

/*-- scss:defaults --*/
$body-bg: #ffffff;
$body-color: #243447;
$primary: #214e70;
$link-color: #175b86;
$font-family-sans-serif: system-ui, sans-serif;
$font-size-base: 1.05rem;
/*-- scss:rules --*/
main.content { line-height: 1.7; }

The defaults section configures variables before theme compilation; the rules section supplies selectors. An ordinary CSS file does not understand Sass variables. Do not simply rename an SCSS file to CSS and expect the variables to work.

Configure the theme and component stylesheet in the project:

format:
  html:
    theme: [cosmo, series.scss]
    css: components.css
    code-copy: true
    toc: true

The base theme supplies a broad design system; the custom theme provides targeted changes. Start with a small set of overrides. Each additional rule increases the number of interactions that must be tested when Quarto or Bootstrap changes.

13.5 Designing a textbook visual identity

The supplied series template uses a white background, dark slate body text, muted blue headings and links, and a teal accent for guided practice. These are proposed design choices, not institutional branding. A restrained palette leaves visual emphasis available for the mathematics itself. Avoid using color as the sole distinction between curves, warnings, or correct and incorrect answers.

A good design system specifies roles rather than arbitrary colors: body text, links, borders, background, instructional emphasis, and error states. Reuse those roles consistently. For long-form reading, prioritize line spacing and reasonable line length over dense decorative layouts. Test a narrow viewport, browser zoom at 200%, keyboard navigation, and code blocks containing long lines.

13.5.1 Mathematical statements

Use semantic theorem blocks for numbered mathematical statements:

::: {#def-linear}
## Linear model
A linear model has the form $y=a+bx$.
:::

Refer to it with @def-linear. Do not hard-code a definition number into its title. If the chapter is moved, automatic numbering should follow the book structure. For explanatory tips and warnings, use standard callouts before inventing custom components. The built-in structures provide more consistent cross-format behavior.

13.5.2 Code presentation

Present R and Python in consecutive sections, with identical mathematical objectives and comparable inputs. Use language-tagged code fences for examples that are not executed. Executable cells use the engine-specific braces described in Chapters 4 and 5. A copy button helps web readers, but printed examples must also include all necessary imports and clearly indicate where data files reside.

13.6 Worked investigation: a reusable model lesson

Suppose a hypothetical instrument produces a signal described by \(S(t)=12+3t\). The intercept is 12 signal units, and the slope is three signal units per time unit. The model is illustrative, not a validated medical device model.

TipInterpretation

At time 4 the predicted signal is \(12+3(4)=24\) units. The slope describes the change in signal per unit of time, not the signal itself.

13.6.1 R implementation

t <- 0:4
signal <- 12 + 3*t
data.frame(t, signal)

13.6.2 Python implementation

t = range(5)
signal = [12 + 3*x for x in t]
print(list(zip(t, signal)))

Both implementations produce the same pairs. The stylesheet must not change these values. This simple example is a useful regression test for a template: change the theme and verify that equations, code, and results retain their meaning.

Time Signal
0 12
1 15
2 18
3 21
4 24

13.7 Format-specific design

HTML uses CSS; PDF produced through LaTeX does not generally use the HTML stylesheet. Word uses document styles, and EPUB depends on the reading application. A common source does not imply identical appearance across formats.

format:
  html:
    theme: [cosmo, series.scss]
    css: components.css
  pdf:
    documentclass: scrreprt
    geometry: [margin=1in]
    include-in-header: print-header.tex
  docx: default
  epub: default

A small LaTeX header can configure paragraph spacing and load microtype for improved typesetting. Avoid redefining complex internal macros until simpler configuration options have been exhausted. For Word, render a sample and use a customized reference DOCX if the publisher requires specific paragraph and heading styles. For EPUB, inspect the result on more than one reader if possible. Official Quarto authoring guidance illustrates how format-specific options can coexist in one YAML file.

13.8 Extensions and Lua filters

An extension packages reusable Quarto functionality. It may contribute a format, shortcode, filter, or other supported feature. A template, by contrast, provides starting files that an author copies and modifies. The two approaches can coexist: a book template may depend on a versioned extension.

Pandoc represents a document as structured elements. A Lua filter can inspect or transform those elements before the writer produces output. The supplied local extension adds an explicit label to each Div carrying the learning-box class.

function Div(el)
  if el.classes:includes('learning-box') then
    table.insert(el.content, 1,
      pandoc.Para({pandoc.Strong({pandoc.Str('Investigation')})}))
    return el
  end
end

This transformation changes content structure, unlike CSS. The label can survive in a non-HTML format even when the colored border does not. The example is intentionally small: a filter should do one well-defined job, and the author should understand its effect before applying it to an entire book.

The extension manifest declares its contribution:

title: Learning Box
version: 0.1.0
contributes:
  filters:
    - learning-box.lua

The local extension lives in _extensions/learning-box/. Activate it in the demonstration project by adding filters: [learning-box] at the root of its configuration. Render before and after activation and compare the output. Third-party extensions can execute code during rendering; inspect their source, provenance, license, and version before installation. Do not install an unknown extension merely because a screenshot looks attractive.

13.9 Reusable publishing templates

The companion examples/ch13/series-template/ directory contains an independent book project with a theme, component stylesheet, print header, optional extension, and model lesson. Copy the entire directory to start a new book, replace metadata, and update the chapter list. Keep a clean reference copy under version control. Record template changes in a changelog and migrate existing books deliberately rather than silently overwriting their local styles.

A release checklist should include HTML navigation, equations, code copying, keyboard focus, narrow-screen layout, PDF page breaks, figure captions, and bibliography formatting. Render each supported format separately. A successful HTML build is not evidence of a successful PDF build.

13.10 Guided practice

  1. Change the primary theme color, render HTML, and identify three elements affected by the change. Check that links remain distinguishable from surrounding text.
  2. Create a guided-practice Div containing a meaningful text label. Disable the CSS and explain which information survives.
  3. Render the model lesson in HTML and PDF. Compare code wrapping, definition numbering, and paragraph spacing. Document differences rather than assuming they are defects.
  4. Activate the local filter, render again, and verify that only the intended Div receives a new label. Remove the filter and confirm that the original content remains intact.

13.11 Troubleshooting

Symptom Diagnostic action
Theme changes not visible Check the theme path and SCSS section markers; inspect computed styles
CSS works only in HTML Configure the other output format separately
Code overflows Test narrow screens and shorten or wrap source lines
Missing extension Check its directory, manifest, and filter name
Duplicate labels Inspect filter behavior and existing manual labels
PDF fails Check the TeX installation and compilation log

13.12 Designing a series-wide visual system

Begin with a small inventory of recurring instructional elements rather than a collection of attractive pages. A definition introduces a mathematical object; a theorem makes a claim under stated hypotheses; a worked example models reasoning; an investigation asks the reader to produce evidence. These roles should remain recognizable even when all color and styling are removed. Reserve numbered theorem environments for statements that readers need to cite later. A decorative panel is not a substitute for a logical hypothesis.

A design token is a named value representing a recurring design decision. For instance, the primary color identifies links and headings, while a secondary accent identifies investigations. Define these values centrally. A change to the primary color should not require a search through hundreds of chapter files. The following specification is a proposed starting point for a mathematics series, not an institutional branding standard.

Token Value Purpose
Ink #243447 Body text
Paper #ffffff Page background
Primary #214e70 Headings and accents
Link #175b86 Underlined hyperlinks
Investigation #26766a Activity border
Activity surface #f2f8f6 Subtle activity background
Reading measure 72ch Approximate maximum prose width

A character-based measure is approximate: the CSS ch unit measures the advance of the zero glyph, not the average character. Do not apply a narrow measure indiscriminately to equations and wide tables. A long matrix or code listing may need a scrollable region or a mathematically equivalent reformulation. On a printed page, a horizontal scrollbar is impossible, so split the expression at meaningful operators.

13.12.1 Laboratory: Quantifying color contrast

Accessibility can be investigated mathematically. For each normalized sRGB channel \(c\), define its linearized value by

\[ f(c)=\begin{cases}c/12.92,&c\leq 0.04045,\\ ((c+0.055)/1.055)^{2.4},&c>0.04045.\end{cases} \]

Relative luminance is \(Y=0.2126f(r)+0.7152f(g)+0.0722f(b)\). For two colors with luminances \(Y_1\geq Y_2\), the contrast ratio is \((Y_1+0.05)/(Y_2+0.05)\). A ratio of at least 4.5:1 is the WCAG AA target for ordinary text, subject to the standard’s exceptions. This calculation does not test keyboard navigation, screen-reader semantics, or the contrast of every component state.

For example, black and white have luminances zero and one, yielding 21:1. Identical colors yield 1:1. The accompanying laboratory calculates contrast for the series palette and deliberately rejects a low-contrast gray. Readers should compare both normal and visited links against their actual backgrounds. Underlining links supplies a non-color cue.

13.12.2 R implementation

luminance <- function(hex) {
  x <- as.numeric(col2rgb(hex))/255
  z <- ifelse(x <= 0.04045, x/12.92,
              ((x+0.055)/1.055)^2.4)
  sum(z*c(0.2126, 0.7152, 0.0722))
}
contrast <- function(a,b) {
  y <- sort(c(luminance(a),luminance(b)))
  (y[2]+0.05)/(y[1]+0.05)
}
contrast('#243447','#ffffff')

13.12.3 Python implementation

def luminance(hex_color):
    c = [int(hex_color[i:i+2],16)/255 for i in (1,3,5)]
    z = [v/12.92 if v <= .04045 else ((v+.055)/1.055)**2.4
         for v in c]
    return sum(a*b for a,b in zip(z,[.2126,.7152,.0722]))

def contrast(a,b):
    lo,hi = sorted([luminance(a),luminance(b)])
    return (hi+.05)/(lo+.05)

print(contrast('#243447','#ffffff'))

13.13 Semantic mathematical environments

Use Quarto’s native theorem syntax when automatic numbering and cross-references are needed. For example, the following definition identifies the concept independently of its visual style.

::: {#def-affine}
## Affine function
An affine function has the form $f(x)=mx+b$.
:::

See @def-affine for the distinction between affine and linear maps.

The word linear has different conventions in school algebra and linear algebra. In linear algebra an affine map is linear only if its constant term is zero. This is a useful example of why a definition must be precise before a designer styles it. Use unique identifiers across the book and avoid typing a theorem number into prose. A newly inserted theorem can change subsequent numbering.

A custom instructional block can instead use a plain Div with a visible label. It does not require automatic numbering. In the following example the label survives removal of the stylesheet.

::: {.investigation}
**Investigation.** Predict the effect of doubling the slope.
Explain your prediction before plotting.
:::

Do not use CSS generated content as the only source of an instructional label. Some output formats ignore CSS entirely, and assistive technology may expose generated content differently. A filter that inserts real document text can be useful, but it must avoid inserting the same label twice. The lab includes an idempotent filter that marks processed blocks with a class and ignores unrelated Divs. Run it twice and compare the output to a single pass.

13.14 Responsive layout and mathematical typography

A page that looks polished at 1440 pixels may be unusable at 320 pixels. Start with the narrowest practical layout and add enhancements for larger screens. Use a single column for the main mathematical argument. Place supplementary material after the argument in source order so that keyboard navigation and linear reading remain coherent. Avoid fixed heights for worked examples: enlarged text and translated labels can exceed them.

Code should remain copyable. Horizontal scrolling is preferable to clipping a long line, but short lines are easier to read and print. Do not insert line breaks into a command merely to make it fit unless the language supports the continuation. Keep R and Python examples in consecutive sections with explicit language labels, matching input data and output precision. The mathematical explanation should precede both implementations so that the reader knows what the computation is intended to establish.

A useful typography test is a long expression containing a fraction, subscript, superscript and matrix. Compare the appearance in HTML and PDF at ordinary reading size. Check whether equation numbers collide with the expression. For example, a least-squares model can be introduced using \(X^TX\hat\beta=X^Ty\) and then expanded into separate equations instead of one extremely wide matrix. Do not imply that solving normal equations is always the preferred numerical method: QR or SVD is often more stable.

13.15 Format-specific editorial decisions

The HTML theme and print header have different responsibilities. CSS can define a responsive reading width, link appearance and focus outlines. A LaTeX header can configure paragraph spacing and typesetting packages. Word output can use a reference document containing paragraph and character styles. EPUB requires checking reflow and reader-specific behavior. Quarto also exposes PDF-specific section numbering and syntax-highlighting settings. Consult PDF Basics when configuring these options.

Avoid adding every available package to the print header. Each additional package introduces possible interactions with the document class and other packages. Test a minimal document before applying a header to an entire book. Do not suppress compilation errors to obtain an apparently successful release. Inspect the log for missing glyphs, unresolved references and overfull boxes. Some warnings are harmless, but their significance must be assessed rather than assumed.

Test HTML PDF Word/EPUB
Definition label Visible and linked Visible and numbered Verify conversion
Long equation No clipping Fits text area Verify equation support
Code Copy and scroll Readable wrapping Editable or readable
Figure Alt text and caption Caption and print legibility Verify placement
Activity Text label and focus Text label without color Text label retained

13.16 Maintaining a reusable extension

An extension is executable publishing infrastructure. Treat a Lua filter as code rather than decoration. Review its source, record its version, and test it on a small fixture before adopting it. A filter can modify headings, links, code or metadata, so a defect may affect the entire book. Prefer a narrowly scoped transformation and avoid network or filesystem side effects for a simple labeling task.

The accompanying fixture contains an investigation and an unrelated note. The filter adds a bold label only to the investigation and marks it as processed. A second pass leaves the result unchanged. This test establishes behavior on the fixture, not on every possible Pandoc document. In a production extension, add tests for nested blocks, empty blocks and existing labels. Keep the extension optional so that an author can still read and render the source without it.

13.17 Release laboratory: Migrating a textbook theme

Imagine that four mathematics textbooks share a theme and one author requests a new activity accent. First create a versioned copy of the template. Run the palette audit, then render a representative chapter with a definition, equation, long code block and figure. Compare the old and new versions at desktop and mobile widths. Check keyboard focus and print a sample page in grayscale. Record the change and the evidence in a migration log. Only then apply the update to other books.

A shared template is not automatically synchronized with every project copied from it. Decide whether to distribute versioned snapshots or use a maintained extension. Snapshots are easy to customize but can drift. A shared extension reduces duplication but increases dependence on a central release. In either case, preserve the previous working version and document local overrides. Avoid changing the appearance of a live textbook during an assessment unless the correction is necessary.

The independent examples/ch13/design-lab/ project includes a miniature book, semantic blocks, a contrast checker, a print header and a filter fixture. Run python audit.py and python test_filter.py before rendering. Inspect the output manually; passing the automated checks is not a declaration of accessibility conformance.

13.18 Extended guided practice

  1. Calculate black-on-white contrast and explain why identical colors yield one.
  2. Compare the body and link colors against white using both languages.
  3. Replace the link color with #bbbbbb. Explain the audit failure.
  4. Remove CSS from the sample investigation. Identify the surviving semantic information.
  5. Add a definition and reference it from a second chapter using a unique identifier.
  6. Run the filter twice and explain why idempotence matters.
  7. Add an unrelated Div and verify that the filter does not alter it.
  8. Compare a long code listing at 320 and 1280 pixels; record actual observations.
  9. Render a print sample and inspect a long equation and a grayscale figure.
  10. Propose a versioned migration plan for three books with different local overrides.

13.19 Extended project: Series design system (30 points)

Create a two-chapter mathematics book using a shared theme. Include a numbered definition, a cross-reference, a worked example, sequential R and Python code, a figure with descriptive alternative text and an investigation with a visible label. Submit a palette audit, filter test, source package, version log and format-specific acceptance evidence. Use a synthetic mathematical example rather than proprietary textbook content. If a renderer is unavailable, mark that test pending.

Criterion Points
Semantic mathematical structure 7
Consistent visual system and contrast 6
Responsive and print design 6
Filter behavior and reproducibility 6
Migration and acceptance evidence 5

13.20 Chapter summary

A maintainable publishing system separates semantic content, configuration, visual styling, and document transformations. Use standard structures wherever possible, keep custom styles small, and test each output independently. A reusable theme is successful when readers can concentrate on the mathematics rather than the interface.

13.21 Review exercises

  1. Distinguish content from presentation.
  2. Explain the role of _quarto.yml.
  3. What does a class selector identify?
  4. Why use relative spacing units?
  5. Explain CSS specificity.
  6. Distinguish CSS and SCSS.
  7. What is the purpose of the SCSS defaults section?
  8. Why prefer semantic theorem blocks?
  9. Explain why HTML CSS does not style LaTeX PDF.
  10. What is a reference DOCX used for?
  11. Distinguish an extension from a template.
  12. What does a Lua filter transform?
  13. Why inspect third-party extensions?
  14. Calculate the model signal at time 7.
  15. Describe two accessibility tests.
  16. Explain why a successful HTML render is insufficient for release.

13.22 Applied project

Develop a reusable theme for a two-chapter mathematics or statistics textbook. Include a definition, a worked example, a guided activity, a table, and sequential R and Python code listings. Configure HTML and PDF separately. Submit the source, rendered outputs, a design rationale, and a test log. If a required engine is unavailable, document the limitation rather than claiming a successful build.

Criterion Points
Semantic organization and mathematics 6
Consistent theme and component styling 5
Format-specific configuration 5
Accessibility and validation 5
Reusable source and documentation 4
Total 25

13.23 Further reading

13.24 Supplemental assessment

  1. Conceptual (4 points). Explain why semantic markup is preferable to styling each theorem manually.
  2. Technical (8 points). Calculate contrast for black on white and white on white; compare with 4.5:1.
  3. Applied (8 points). Create a shared theme for Book 1 and Book 2 with a print alternative.

See the student assessment packet in the source package for submission guidance and any required datasets.

13.25 Looking ahead

Track revisions to content and design using Git in Chapter 14.

13.26 Interactive learning lab

Explore the activity below, then explain what changed and why.

Open the activity in its own page.