When writing a print stylesheet, is there a way to ensure that an image is always only on a single page, instead of spanning multiple pages. The images much smaller than the page, but based on the document flow, they end up at the bottom of the page and get split. An example of the behavior I'm seeing is below:
Page 1 | |
| (text text text) |
| (text text text) |
| ________________ |
| | Top of image | |
|____________________|
------page break------
____________________
Page 2 | | Rest of image | |
| |________________| |
| … |
What I'd like
Page 1 | |
| (text text text) |
| (text text text) |
| |
| |
|____________________|
------page break------
____________________
Page 2 | ________________ |
| | Full image | |
| | | |
| |________________| |
| … |
All those times I complained about floats in LaTeX, and here I am asking for the same functionality... Can this be done? I'm not necessarily concerned about it working in all browsers, since this is often just a one-off document I'm writing to be turned into a PDF.
You can use some combination of the following well-supported CSS rules to control this behavior:
img {
display: block; /* to override flexbox behavior */
break-inside: avoid; /* applies the behavior you're asking for */
page-break-inside: avoid; /* fallback for older browsers */
/*
poorly supported across browsers [1], but possibly interesting:
- break-before / page-break-before, initially 'auto'
- break-after / page-break-after, initially 'auto'
*/
}
The break-after
, break-before
, and break-inside
variants are modern replacements for the now-deprecated page-break-after
, page-break-before
, and page-break-inside
properties.
The break-inside
property applies to “all elements except inline-level boxes, internal ruby boxes, table column boxes, table column group boxes, absolutely-positioned boxes”3, so display: block;
or similar might be necessary for the images themselves or their parent paragraph, div, span, list, etc. The current spec defines many more values such as recto
and verso
which are not currently supported across the board, but only make sense for complicated print layouts.
Also keep an eye out for <figure>
s or other container elements, which may have non-default position or flexbox properties applied to them, as noted in this SO answer. Here, the browser's dev tools are your friend.
Some other useful discussion here:
media="print"
specific, cross-browser compatible CSS properties?References: