Responsive Ebook Design: A Primer

Modern websites largely fulfill the promise of being device-agnostic, but our ebooks are lagging behind. A look at how publishers can adopt responsive practices to build better digital books.

Sanders Kleinfeld
24 min readJan 5, 2015

Dear Publisher,
Your book looks like 💩 on my 📱. Please fix.
— Customer

In the book publishing industry, we tend to cotton to one of three prevailing schools of thought on how to accomplish ebook design.

One favored paradigm is the fixed-layout approach (pioneered by Apple and codified as an IDPF EPUB specification), which stipulates that “page” dimensions are rigidly set, and text and graphics must be painstakingly manually laid out on each page spread. Fixed-layout ebooks are destined for a predetermined platform (typically iPad or Kindle Fire) and customized to its reading-system specifications, which guarantees that consumers of the content will see exactly what the designer envisioned.

On the other end of the spectrum is a philosophy of design nihilism, characterized by Nietzschean indifference to the enterprise of styling content for an ebook ecosystem in which HTML5 and CSS3 support fluctuate greatly, and the results of loading a lovingly crafted EPUB 3 to any given device may make the jaw drop in horror. Design nihilists want ebook content to be available across all ereader platforms (rather than siloed to a specific device, as in fixed layout) but are understandably jaded about what can be pragmatically achieved, and thus settle for lightweight, lowest-common-denominator CSS styling that is guaranteed to work across all platforms.

Splitting the difference is the strategy I dub the Heinz method, in which designers create 57 ebook varieties—one for iBooks, one for NOOK Color, one for Kobo GLO, etc.—such that each file can be subtly (or sometimes, not so subtly) optimized to suit the constraints and tics of its host. This enables design customization for a diversity of ereaders, but at the expense of inordinate effort; see Craig Mod’s “Platforming Books” for an enlightening case study on the production legwork necessary to accomplish this task for a single title, for just a handful of devices.

Any one of the above paradigms may well suit a given publisher’s needs; fixed layout is a great fit for graphic novels or children’s books, and barebones styling may be perfectly sufficient for novels. But oftentimes, these approaches entail distasteful compromises—e.g., content restricted to one ereader platform, lower-caliber design, or cost-ineffective expenditure of resourses.

The missing component in all three philosophies is a focus on responsive design: the methodology that web developers and designers began cultivating at the advent of the smartphone era to facilitate creation of a universal set of web assets that yield high-quality results optimized for all devices. There’s no reason publishers shouldn’t strive to achieve these same goals, to commit to an analogous philosophy of responsive ebook design.

An ebook is not the same as a web application, however, and an ereader is not the same as a web browser. As such, the precepts of responsive ebook design must be tailored to the unique contours of the medium, where:

  1. Content is split into pages.
    While a handful of reading systems (e.g., iBooks) have a “scrolling mode” in which content is presented in one long scroll like a single web page, most major ereaders default to a paginated view, in which the text is split into a series of “pages” that users can navigate through linearly. Responsive design for ebooks entails optimizing the layout of content delivered in these arbitrarily sized pages, where the location of page boundaries depends largely on the device’s screen dimensions.
  2. Content reflows among these pages.
    A fixed-layout approach, where designers expressly earmark a specific chunk of content for a specific page, is entirely antithetical to the endeavor of responsive design. If pages are arbitrarily sized to account for a multiplicity of screen form factors, then content must be allowed to flow freely through those pages, or aesthetics will vary widely (and often unpleasantly) across platforms.
  3. Content adapts to a user-configurable ereader environment.
    Ebooks are by definition “longreads,” and ereader settings are by design highly user-configurable to facilitate people’s ability to adjust display specs for a screen at which they’ll be staring for many hours. Responsive ebook design strives to account for individual customization of features such as font face, text size, screen brightness, etc., as much as feasible.
  4. Content is encapsulated in a single, universal archive of assets for all ereader platforms.
    As currently defined by both of its leading specifications, EPUB and MOBI, an ebook is a discrete archive of content and metadata assets. Those that create separate custom files for each ereader platform are not making a responsive ebook; they’re making dozens of unresponsive ebooks. For the term responsive to describe an ebook in any meaningful fashion, it must be associated with a single, universal file, just as a responsive website is associated with a single, universal URL.

In this article, I describe a series of responsive-ebook best practices—from media queries to pagination hacks—that stem from the principles above. I provide example-based guidance on real-world implementation in contemporary ereading platforms (with a focus on iBooks and Kindle), culled from both my own research and that of other ebook developers. I also advocate for upcoming, bleeding-edge specifications with the potential to further augment the responsive capabilities of ebooks.

Media Queries

Media queries are CSS conditionals, which allow you to selectively apply styling based on two categories of user-agent parameters: the output medium (called media type), and its display properties, called media features. A media-query block in CSS takes the form:

@media query_parameters {
/* CSS properties to be applied if query_parameters are true */
}

Where query_parameters typically consist of an optional single media-type value of screen (any onscreen display) or print (for output printed to paper), followed by one or more media features, which include width and height to style based on the size of the viewport; orientation to style based on whether the screen is portrait or landscape; and monochrome or color to style based on color support of display. Parameters are concatenated by the and operator, and each media feature must be delimited by parentheses.

The following example shows a media query in which styling is applied to content when the viewport width is at least 400 pixels wide and at least 600 pixels tall:

@media (min-width: 400px) and (min-height: 600px) {
/* properties here will be applied only if the viewport
is at least 400px wide and 600px tall */
}

For further explanation of media queries, see the W3C “Media Queries” specification, which provides comprehensive documentation and examples.

CSS media queries are formally included in the EPUB 3 CSS Profile, which means that they should be supported in all EPUB 3–compliant ereaders. And in fact, they are supported to varying degrees in both EPUB 3 on Apple iBooks, as well as in MOBI on the Kindle ecosystem.

Media Queries in iBooks

Good news for EPUB 3 developers in iBooks: you can indeed use media queries to distinguish between iPhone and iPad platforms, as well as portrait and landscape orientation—with the slight caveat that user-agent eccentricities can entail workarounds that can make this task a bit of a headache at times.

For a proof of concept, I created an EPUB 3 file called “iBooks Ereader Detector,” which includes the following XHTML5:

<h1>iBooks Ereader Detector</h1>
<p>You are likely reading this ebook:</p>
<ul>
<li><span id="platform_device">On&#xa0;</span></li>
<li><span id="orientation">In&#xa0;</span></li>
</ul>

I was then able to dynamically update the #platform_device and #orientation list items using CSS containing a series of media queries that made use of three media features: width, device-width, and orientation. I used min-device-width and max-device-width to query for the absolute screen-width dimensions of iPhone and iPad (as reported by Stephen Gilbert), and orientation to ascertain whether the device display was portrait (width < height) or landscape (width > height). However, iBooks for iPad posed some specific orientation challenges due to viewport quirks specific to landscape display in paginated view (where two pages are displayed side by side). As Liza Daly notes, in landscaped page view, iBooks considers the two pages to be “distinct portrait viewports,” but I found that in iBooks v4, it was possible to distinguish these smaller pages from a single portrait mode using different width values, as Derrick Schultz has documented.

Here is the relevant annotated CSS I added to my EPUB:

/* Media query order matters here, as content of later media queries will override that of earlier ones) */

/* Default orientation handling */

@media (orientation:landscape) {
#orientation::after {
content: "landscape mode";
}
}

@media (orientation:portrait) {
#orientation::after {
content: "portrait mode";
}
}

/* iBooks Platform Queries */

/* Standard iPad device pixel dimensions */

@media (min-device-width:768px)
and (max-device-width:1024px) {
#platform_device::after {
content: "iBooks for iPad";
}
}

/* Standard iPad device pixel dimensions + two-up landscaped viewport (in landscape view for iPad, each page is a separate viewport which is less than 480 px) */
@media (min-device-width:768px) and
(max-device-width:1024px) and
(max-width: 480px) {
#orientation::after {
content: "landscape mode (two-up view)";
}
}

/* Should work on iPhone 5s and below */
@media (max-device-width:480px) {
#platform_device::after {
content: "iBooks for iPhone";
}
}

The following screenshots illustrate the resulting rendering in iBooks 4 on iPad 3 Retina and iPhone 5S, in both portrait and landscape modes.

iBooks Ereader Detector successfully distinguishes iBooks on iPhone 5S in portrait mode (top left), iBooks on iPhone 5S in landscape mode (top right), iBooks on iPad 3 Retina in portrait mode (bottom right), and iBooks on iPad 3 Retina in landscape two-up mode (bottom left).

iBooks Ereader Detector EPUB and full CSS code (which include additional media queries for iBooks Desktop for Mac) are available on GitHub; bug reports and pull requests welcome.

For a more real-world example of media queries used on iBooks to implement responsive design, see Liza Daly’s illustrated poetry example from her article “Create rich-layout publications in EPUB 3 with HTML5, CSS3, and MathML.”

Media Queries for Kindle

Kindle actually arguably eclipses iBooks in terms of its media query support, adding to its KindleGen software two custom media types (not formally included in the W3C Media Queries specification) for targeting platforms that support the KF8 file format (e.g., Kindles Fire and Paperwhite) vs. those that don’t (e.g., first-generation Kindle DX): amzn-kf8 and amzn-mobi, respectively. These queries make it possible to provide fallback styling for non-KF8 Kindle devices, which don’t support as wide a range of CSS properties as KF8-enabled platforms.

A typical use case for @media amzn-mobi and @media amzn-kf8, as recommended in Chapter 8 of the Amazon Kindle Publishing Guidelines, is to employ display: none to toggle on/off display of elements based on the targeted platform, e.g.:

@media amzn-mobi {
table.complex {
/* Suppress display of complex tables on MOBI and use fallback image instead */
display: none;
}
}

@media amzn-kf8 {
img.table_fallback {
/* Suppress display of table fallback images on KF8, which can support complex tables */
display: none;
}
}

@media amzn-kf8 and @media amzn-mobi are quite useful, but alone, they cannot distinguish between two KF8 platforms or two legacy MOBI platforms, and are not helpful if you want to target styling for just Kindle Paperwhite or just Kindle Fire. Fortunately (as documented by Derrick Schultz, Peter Hatch on the Extraordinary Commons blog, and William Ockham and the grassroots experimentation of the MobileRead community), like iBooks, KindleGen also supports the device-width and device-height media features for targeting specific Kindle platforms based on device screen dimensions.

In the following example, device-width and device-height have been added to the second @media amzn-kf8 query, in order to override paragraph first-line styling for the Kindle Paperwhite platform only:

/* Applied on any KF8 platform */
@media amzn-kf8 {
p:first-of-type::first-line {
color: green;
}
}

/* Overrides specific to Kindle Paperwhite */
@media amzn-kf8 and (device-height: 1024px) and
(device-width: 758px) {
p:first-of-type::first-line {
color: black;
font-variant: small-caps;
}
}

The following side-by-side screenshots illustrate the resulting rendering on Kindle Paperwhite vs. Kindle Fire.

KF8 rendering differently cross-platform on Kindle via media queries: on Kindle Previewer, with first line in smallcaps (left) vs. on Kindle Fire HD, with first line in green (right)

What about monochrome vs. color?

Oftentimes, it’s less important to tailor design to a specific device or set of screen dimensions than it is to target specific display properties—one notable example being whether the display is monochrome or color. In this case, writing queries using device-width and device-height to isolate specific devices (e.g., Kindle Paperwhite vs. Fire) by screen dimensions as a proxy for color support is rather clunky—and potentially also less future-proof should specifications change in future hardware models.

A more elegant way to distinguish devices by their color space is to use the media features expressly designed for this purpose, aptly named monochrome and color, as shown in the following queries:

@media (monochrome) {
/* This CSS is targeted at monochrome devices only */
}

@media (color) {
/* This CSS is targeted at color devices only */
}

Unfortunately, despite the fact that the Kindle Publishing Guidelines assert that monochrome is supported for KF8, this was not borne out in my own testing, where @media (monochrome) was ignored on KF8 devices.

I also tried using the color media feature to specify “not color” via both the media queries @media not (color) and @media (color: 0), but neither of these queries worked as expected. In the case of color, Kindle does not ignore the query, but instead inaccurately considers both monochrome and color KF8 devices (both Paperwhite and Fire) to be color displays (with an 8-bit color system), which effectively makes it impossible to reliably distinguish between these two types of platforms based on media-query-reported color support. So, at least for the time being, those who want to craft different CSS for Kindle monochrome and color devices do indeed need to fall back on querying for each device separately by screen dimensions.

Monochrome-versus-color querying is less relevant within the iBooks ecosystem, as all its platforms currently have color displays. However, in my own testing, I found that iBooks ignored media queries containing monochrome, and returned true (indicating an 8-bit color system) for queries using color—e.g., @media (color) and @media (color: 8)—should there prove to be a relevant use case for employing them.

Media Queries for both iBooks and Kindle

Media queries are even more useful to publishers when they can be used across proprietary vendor ereader ecosystems. Extant support for media queries on both Apple and Amazon platforms currently makes it possible to achieve the goal of supplying the same EPUB 3 file to iBooks and Kindle (via KindleGen conversion to MOBI), while still employing some degree of CSS customization on a per-device basis.

One popular approach for targeting both Kindle and iBooks with a single EPUB is to divide the ebook design into two separate categories: one set of styling for both iBooks and KF8-enabled Kindles (whose CSS support is reasonably comparable with that of EPUB 3), and one set of “fallback” styling for legacy Kindle devices that support only MOBI 7's much more limited set of CSS properties. Each set of CSS can then be encapsulated with media queries.

For legacy MOBI, the query is straightforward:

@media amzn-mobi {
/* This styling will only be applied to MOBI 7 platforms */
}

For KF8 and iBooks, one approach might be to use a comma-separated list of the media queries documented in the previous two sections, e.g.:

@media amzn-kf8, 
(min-device-width:768px) and (max-device-width:1024px), ...
{
/* Styling applied to all platforms matching
one of the above queries
*/
}

However, if all that’s needed is a query that will match everything that is not MOBI 7, it’s possible to simplify to the following query using the not keyword (which matches the exact opposite of @media amzn-mobi):

@media not amzn-mobi {
/* Styling for everything that _is not_ a MOBI 7 platform */
}

Liz Castro provides a real-world example of this approach in action in her article, “Media Queries for formatting Poetry on Kindle and EPUB,” where she walks through the CSS styling for optimizing the rendering of a stanza of Whitman poetry on iBooks and Kindle.

Media Queries:TNG (a.k.a. Media Queries Level 4)

The W3C’s Media Queries specification continues to evolve, and the latest iteration, Media Queries Level 4 (still in Working Draft status), adds some new media features that should be of particular interest to many ebook developers. None of the following features are supported yet in the greater ereader ecosystem, but the digital-publishing community should begin to advocate for their adoption if they believe they would find them valuable in developing more responsive designs for their content:

overflow-block— Enables queries based on the user agent’s handling of content that flows beyond the boundaries of the screen. Accepts the following enumerated values: none (overflow content is truncated and not displayed), scroll (overflow content is accessible by scrolling the screen), optional-paged (by default, overflow content is accessible by scrolling, but content creators can also specify formal breakpoints to paginate content as desired), and paged (content is split into distinct pages).

Relevant use case for ebooks: Use the queries @media (overflow-block: scroll) and @media (oveflow-block: paged) to distinguish between Scrolling View and Paged View, respectively, in ereaders that support one or both of these modes to customize CSS styling accordingly.

light-level Enables queries for the amount of ambient lighting present in the surrounding environment (for platforms like smartphones and tablets that have light sensors). Accepts the following enumerated values: dim (low lighting), normal (appropriate amount of lighting), and washed (high level of lighting, resulting in “washed out” display).

Relevant use case for ebooks: Use the query @media (light-level: washed) to adjust text/background contrast to optimize reading in high-light settings, such as a sunny day on the beach.

update-frequency— Enables queries based on the refresh rate of the screen, a good metric for distinguishing LCD tablet screens from E Ink displays (which are relatively slower to update). Accepts the following enumerated values: none (display cannot update at all; basically printouts, so effectively the equivalent of @media print), slow (slow refresh rate; not suitable for animations), and normal (refresh rate fast enough to be suitable for animations).

Relevant use case for ebooks: Use the query @media (update-frequency: normal) to silo CSS transitions so that they are not applied to E Ink devices.

inverted-colors Matches displays in which colors have been inverted (e.g., Night View on many ereader platforms). Boolean query that also accepts the following enumerated values: none (screen colors not inverted) and inverted (screen colors inverted).

Relevant use case for ebooks: Use the query @media (inverted-colors) to provide CSS overrides to customize styling when display is in Night View mode, in cases where ereader software defaults would otherwise provide less than ideal results, as in the side-by-side comparison below.

Excerpts from Apple’s The Swift Programming Language on iBooks 4 for iPad 3 with inverted screen in Night View (left) and with original colors on a white background (right). The availability of inverted-colors in iBooks would make it possible to better adapt code syntax highlighting styling so that it would not be completely lost in the white-on-black environment.

Multiple Renditions

Sometimes media queries alone are not enough. In order to further optimize ebooks for different ereader platform specifications, it’s often desirable to adjust content assets in addition to CSS styling. For example, an electronics ebook with color diagrams may require text and image adaptations for monochrome screens (the caption “Figure 1.1—Whatever you do, don’t cut the green wire!” might be a problem for Kindle Voyage readers).

At present, the “57 varieties” strategy—create a distinct, custom EPUB/MOBI file for each target platform—is really the only viable mechanism for accomplishing this goal. But this approach entails a steep cost in terms of inefficiencies in file management and distribution.

As a means of addressing these challenges, in December 2014 the IDPF released a new proposed specification, “EPUB Multiple-Rendition Publications 1.0,” whose goal is to ease the burden of maintaining ebook variants by introducing formalized metadata conventions for bundling these distinct content renditions in a single EPUB container, syncing navigation points between them, and instructing reading systems which one to display.

Multiple Renditions offers a couple of key efficiencies to publishers currently making more than one EPUB file for a single title. First, it can eliminate a good deal of redundancy, as the spec permits content assets to be shared across any variants packaged in the same EPUB container. (If an HTML chapter file requires errata revisions and is shared by all renditions in the EPUB container, the content only needs to be updated once, in one place—as opposed to several times in several different ebook archives that must carefully be kept in sync.) Second, it streamlines ebook distribution, as a single “universal” EPUB file can potentially be delivered to all ebook vendors, placing the burden of selecting and delivering the appropriate rendition on the retailer or ereader platform.

Embedding multiple renditions in EPUB

There are three requirements for embedding multiple renditions of an ebook inside a single EPUB file. First, the EPUB must include a META-INF/metadata.xml file that contains universal metadata for all renditions, which must include at minimum a unique publication identifier (see Publication Metadata in the spec for more details and an example). Second, each rendition must be uniquely identified by a distinct OPF Package Document that contains its metadata, manifest, and spine (sequencing in which assets should be rendered). Third, each rendition’s OPF file must be referenced in a distinct <rootfile> child element of <rootfiles> in the EPUB’s META-INF/container.xml file, e.g.:

<rootfile full-path="OEBPS/greatexpectations.opf"
media-type="application/oebps-package+xml"/>

Each <rootfile> may contain one or more of four rendition-selection attributes, which identify the rendition’s purpose to the reading system:

rendition:accessMode — Rendition content is categorized by a specific mode of communication. Accepts one or more of four enumerated values: auditory (content is primarily audio-based), tactile (content is primarily conveyed via touch — e.g., Braille), textual (content is primarily written language), and visual (content is primarily graphics/video).

The following <rootfile> element identifies an audio rendition:

<rootfile full-path="OEBPS/greatexpectations_spoken.opf"
media-type="application/oebps-package+xml"
rendition:accessMode="auditory"/>

rendition:language— Rendition content is associated primarily with a specific language. Accepts a valid language code as its value.

The following <rootfile> element identifies a rendition in Japanese:

<rootfile full-path="OEBPS/greatexpectations_ja_translation.opf"
media-type="application/oebps-package+xml"
rendition:language="ja"/>

Rendition variation by language should not be perceived as being limited solely to changes in text content. There’s also a dimension of responsive design that is quite relevant to linguistic variation. Languages differ in required character set support (English has 26 lowercase letters; Japanese has ~50,000 kanji characters), and writing direction (Italian is written left to right; Arabic is written from right to left). It may be desirable, for example, to change CSS font declarations (@font-face/font-family) or margin handling to accommodate these sorts of differences.

rendition:layoutRendition content is intended for either a reflowable or fixed-layout context. Accepts one of two enumerated values: reflowable (reflowable context) or pre-paginated (fixed-layout context).

The following <rootfile> element identifies a rendition to be used in a fixed-layout context:

<rootfile full-path="OEBPS/greatexpectations_color.opf"
media-type="application/oebps-package+xml"
rendition:layout="pre-paginated"/>

rendition:mediaRendition is associated with a specific set of media feature conditions. Accepts a valid media query (sans opening @media declaration and media type) as its value.

The following <rootfile> element identifies a rendition targeted for color displays:

<rootfile full-path="OEBPS/greatexpectations_color.opf"
media-type="application/oebps-package+xml"
rendition:media="color"/>

Here is an example of a full container.xml file that lists three available renditions:

<container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container" xmlns:rendition="http://www.idpf.org/2013/rendition">
<rootfiles>
<rootfile full-path="OEBPS/default.opf"
media-type="application/oebps-package+xml"/>
<rootfile full-path="OEBPS/color-reflow.opf"
media-type="application/oebps-package+xml"
rendition:media="color"/>
<rootfile full-path="OEBPS/ipad-reflowable.opf"
media-type="application/oebps-package+xml"
rendition:layout="reflowable"
rendition:media="min-device-width:768px"/>
</rootfiles>
</container>

Ereaders that comply with Multiple Renditions are required to use the algorithm defined in the specification’s “Processing Model” section to choose which rendition to display: Starting with the last <rootfile> entry in the list and moving backward, the reading system should review each entry. If all the entry’s rendition: attributes are true based on device specs and/or reading environment settings, that entry’s rendition should be displayed. If an entry has a rendition: attribute that is false, or does not have any rendition: attributes, the reading system should move on to the preceding <rootfile> entry and review it in the same fashion. The first <rootfile> in the list should be considered the default and be rendered if none of the other renditions are suitable.

In the preceding example, the final <rootfile> specifies both rendition:layout of “reflowable” and a rendition:media of “min-device-width:768px”. If the reading system is in reflowable mode and the device has a screen width of at least 768 pixels, then this rendition should be displayed. If not, the second <rootfile> specifies a rendition:media of “color,” so if the display supports color, this rendition should be displayed. If not, the reading system should fall back on the first <rootfile>’s rendition by default.

Can I use Multiple Renditions right now?

As of December 2014, I’m not aware of any ereader platforms that support Multiple Renditions. However, there’s no real harm in packaging additional renditions into EPUB files, and doing so would make ebooks forward-compatible with future ereader software iterations that build functionality around the spec. Both the EPUB 2 and EPUB 3 OCF specifications instruct reading systems to consider the OPF document referenced in the first <rootfile> in container.xml to be the default, so as long as you structure the EPUB’s <rootfiles> list accordingly, your desired default rendition should display as expected in reading systems that don’t support Multiple Renditions.

That said, reconfiguring workflows and updating tooling to produce Multiple Rendition EPUBs is a nontrivial effort, and content creators likely won’t find it a worthwhile investment until at least one of the major ereading platforms adds support (which will hopefully happen soon!).

Pagebreaking and Adaptive Layout

One of the biggest challenges of producing highly designed ebook content is ensuring content is paginated nicely. The fixed layout spec is appealing because it provides a definitive approach for delineating page boundaries: mark up each two-page spread separately, to the exact screen-dimension specifications of your target ereader platform. But fixed-layout content is by definition unresponsive; it focuses on a single reading platform and thwarts user efforts to customize display settings such as type size and font face. It’s a sledgehammer solution not particularly suited to the nuances of a delicate problem.

Thus, the challenge is to replace that sledgehammer with a scalpel. We want to produce the standard, reflowable EPUB 3 or KF8 file, but still retain a reasonable level of control over content pagination and layout. The following sections explore several strategies for pagebreaking and layout in a reflowable context.

“Hard” pagebreaks

A hard pagebreak is an invisible, dashed horizontal line drawn across your content, saying “Start a new page here!” CSS 2.1 supports the insertion of hard pagebreaks via two properties: page-break-before and page-break-after, which, when set to a value of always, force a pagebreak either before or after the designated element, respectively. The following CSS indicates that hard pagebreaks should be created before h1 elements, so that these headings will always begin on a new page:

h1 { page-break-before: always }

Both page-break-before and page-break-after are honored by iBooks and Kindle KF8 reading systems.

Hard pagebreaks are easy to insert, but they should be employed sparingly in responsive ebooks, as their overuse effectively regresses to a fixed-layout paradigm that limits the flexibility of content to adapt to different screen dimensions. If you use page-break-before to optimize every page boundary for one platform, you may be unpleasantly surprised with the results on another, where there may be unintended short pages.

“Soft” pagebreaks

A better, more responsive method of adjusting page boundaries is to use soft pagebreaks. Rather than mandating, “Start a new page here!”, soft pagebreaks are conditional instructions, which suggest the placement of pagebreaks based on current page geometry.

A popular and useful form of soft pagebreak available in CSS is the page-break-inside property, which accepts a value of avoid to indicate that, whenever possible, the reading system should not insert a pagebreak within the content of the designated element.

The following CSS indicates that a page boundary should not split the content of pre elements with a class of poem, and results are shown in the screenshots below:

pre.poem { page-break-inside: avoid }
Poem excerpt from Through the Looking-Glass in iBooks for Mac. At left, poem is typeset so that it is not interrupted by a page boundary using page-break-inside: avoid. At right, the same poem is typeset without any pagebreaking CSS, and spans a page boundary.

page-break-inside: avoid is supported by iBooks, but is ignored on Kindle KF8 platforms. When typesetting for both platforms, you may want to use media queries (see “Media Queries for Kindle,” earlier in this article, for more on this topic) to specify fallback pagebreaking for Kindle, e.g.:

pre.poem { page-break-inside: avoid }

@media amzn-kf8 {
pre.poem { page-break-before: always }
}

Soft pagebreaks can also theoretically be implemented with page-break-before: avoid and page-break-after: avoid. The following CSS indicates that a pagebreak should not be inserted prior to the first paragraph following a h1, specifying that a top-level heading should be kept on the same page as the subsequent paragraph:

h1 + p { page-break-before: avoid }

However, I’ve found that the above CSS pagebreaking instruction is not consistently obeyed in either iBooks or Kindle, so this approach is not widely usable at this time.

When employed judiciously, the page-break-before, page-break-after, and page-break-inside CSS properties are quite powerful, but the granularity of their control extends only to the level of specifying locations where breaks can occur between elements. They do not permit you to suggest locations for a pagebreak within elements. In other words, you can specify page-break-inside: avoid on a pre element to require that a pagebreak fall before or after its content, but you cannot use this property to specify that a pagebreak is permitted to fall anywhere after the first four lines of its content or before the last four lines of its content.

To achieve additional intraelement granularity at the line level, there are two other CSS properties available: orphans and widows. The orphans property allows you to specify the minimum number of lines of content within an element that must be preserved before a page boundary (i.e., at the bottom of a page), and the widows property allows you to specify the minimum number of lines of content within an element that must be preserved after a page boundary (i.e., at the top of a page). Both properties have a default value of 2, and are typically set on a global basis (e.g., to make sure all paragraphs are typeset such that they have no fewer than 2 lines “orphaned” or “widowed” at the bottom or top of a page).

However, it’s easy to customize widow and ophan properties for different elements. In the following CSS, widows and orphans are set to 4 for pre elements with a class of poem:

pre.poem {
widows: 4;
orphans: 4;
}

The screenshot at below-left illustrates the results; compare to the screenshot at below-right, where page-break-inside: avoid was used instead, forcing the entire second poetry block to the recto page.

Soft pagebreaking of a poem excerpt from Through the Looking-Glass in iBooks for Mac. At left, second “Jabberwocky” poem is pagebroken using widows: 4 and orphans: 4, and spans the page break with more than four lines on either side. At right, second “Jabberwocky” poem is pagebroken using page-break-inside: avoid, and is pushed to the second page.

EPUB Adaptive Page Layout

Soft and hard pagebreaks are powerful tools for optimizing pagination of responsive ebook content, but they fall short of fixed-layout design in one key area. Pagebreaking alone can’t bring the sort of sophisticated layouts possible in a fixed context, where each element can be absolutely positioned on a set canvas, to a reflowable context, where content must dynamically adapt to different screen dimensions.

To fill this gap, the IDPF developed a new EPUB Adaptive Layout specification, whose mission is to support “magazine-style” design for reflowable EPUB. Adaptive Layout comprises a set of CSS extensions (prefixed with -epub or -epubx), which facilitate the creation of book templates containing master pages (@-epubx-page-master), broken up into distinct “partitions” (@-epubx-partition) into which HTML elements can be flowed based on user-defined rules.

Features of EPUB Adaptive Layout include:

A detailed explanation of Adaptive Layout is beyond the scope of this article. To learn more, I highly recommend the series of progressive tutorials and corresponding sample files created by Peter Sorotokin (coeditor of the specification), which walk through building adaptive-layout CSS stylesheets step by step.

At present, no major ereading platforms support the Adaptive Layout CSS extensions (the spec is currently in Informational Document status). However, Sorotokin has released an open source, JavaScript browser implementation available for download on Google Code, which is relatively easy to install on a web server. Additionally, desktop viewers are available for both Mac and Windows OSes on Sorotokin’s site.

The following screenshots from a live demo created by Sorotokin illustrate an adaptive-layout CSS rendering of the text of Wikipedia’s Apollo 8 entry on Mobile Safari for iPad and iPhone.

“Apollo 8" Adaptive Layout EPUB demo by Peter Sorotokin, rendered in Mobile Safari for iPad 3 (left) and iPhone 5S (right)

There has been some lively debate about the merits of both the EPUB Adaptive Layout specification and the CSS Regions module on which its partition module was originally based, and it’s a bit unclear right now as to what the future holds for either specification. Regardless, the Adaptive Layout initiative is clearly an impressive proof of concept of what’s currently achievable on the web stack. I’m optimistic that it will serve as a jumping-off point for future exploration in this space (such as the Vivliostyle project), which will ultimately bear fruit for publishers looking for open-standard, responsive alternatives to fixed layout. Stay tuned!

Bibliography/Further Reading

Amazon Kindle Publishing Guidelines, 2014.

Bjarnason, Baldur. “On CSS Page Templates,” March 2, 2012.

Castro, Liz. “Media Queries for formatting Poetry on Kindle and EPUB,” January 15, 2012.

“CSS Fragmentation Module Level 3,” W3C Working Draft, January 16, 2014.

“CSS Regions Module Level 1,” W3C Working Draft, October 9, 2014.

Daly, Liza. “Create rich-layout publications in EPUB 3 with HTML5, CSS3, and MathML,” July 5, 2012.

“EPUB Adaptive Layout,” IDPF Informational Document, 2011–2012.

“EPUB 3 Fixed-Layout Documents,” IDPF Informational Document, 2012.

“EPUB Multiple-Rendition Publications 1.0,” IDPF Proposed Specification, December 2, 2014.

“EPUB Publications 3.0.1,” IDPF Recommended Specification, June 26, 2014.

Gilbert, Stephen. “CSS Media Queries for iPads & iPhones.”

Gylling, Markus and Ivan Herman. “Advancing Portable Documents for the Open Web Platform: EPUB-WEB,” Unofficial Draft, November 21, 2014.

Hatch, Peter. “Media Query Values for Kindle Fire (Previewer),” January 26, 2012.

“Help improve Kindle ebook formatting,” MobileRead Forums, March 29, 2013-.

Marcotte, Ethan. “Responsive Web Design,” May 25, 2010.

“Media Queries,” W3C Recommendation, June 19, 2012.

“Media Queries Level 4,” W3C First Public Working Draft, June 5, 2014.

Mod, Craig. “Platforming Books,” August 2012.

“Requirements for Latin Text Layout and Pagination,” W3C Editor’s Draft, November 14, 2014.

Schultz, Derrick. “iBooks media queries differ for scrolling vs pagination,” May 11–12, 2014.

Schultz, Derrick. “Media Queries for Kindle Devices,” May 14, 2014.

Sorotokin, Peter. “Adaptive Layout.”

Wium Lie, Håkon. “CSS Regions Considered Harmful,” January 22, 2014.

Title image “λάστιχο, rubber bands by Bill Ebbesen” by Duncan Hull (https://www.flickr.com/photos/dullhunk/6827669146/in/photostream/)

--

--