CSS styles for printing that I forgot about. Html - pages - page-break-after not working printable html page break



I got hooked on this tweet. I suddenly realized that I couldn't remember when I optimized web pages for printing, or at least checked how they were output to the printer.

The main attention in the course of web development is focused on electronic versions of sites. Pages have to be checked in many browsers, tested on different window sizes ... Are there printers here. Or maybe I forgot about styles for printing because I rarely make paper copies of pages myself. Be that as it may, I felt that the situation urgently needed to be corrected.

The printed version of the web page has the same right to exist as the electronic one. And, if we strive to make our materials as accessible as possible, do not neglect paper media. In addition, you should not make assumptions about users and their behavior. People still print web pages on printers. Just imagine articles or blog posts, recipe pages, contact details, driving directions, or listings of ads. Sooner or later, someone will certainly try to print something from what you have posted on the Internet.

Here is what Haydon Pickering, author of Inclusive Design Patterns, says about this: “I haven’t used a home printer for a long time. The point here is that I get the feeling that they break ten minutes after you start printing. But I am not everything. "

If by now you realize that, like me, you did not pay enough attention to the styles for printing, I hope my story will serve you well and help you quickly refresh your memory. And if you've never optimized web pages for printers at all, my small collection of useful CSS tricks will get you started.

1. Using CSS Styles for Printing

The best way to include printable styles on a page is to declare an @media rule in your main CSS file.

Body (font-size: 18px;) @media print (/ * there will be print styles * / body (font-size: 28px;))
Alternatively, you can put the styles for printing into a separate file and include it in HTML, but with this approach you will need an additional request when loading the page.

2. Testing

How do you evaluate the appearance of a print-ready web page? It is clear to anyone that putting it on paper after every style change is not the best solution. Fortunately, the capabilities of browsers are sufficient for paperless checking of printed page variants.

Depending on the browser, you can export the page to PDF, use the preview function, or even debug the page right in your web browser.

To debug print styles in Firefox, open Developer dashboard using the keyboard shortcut Shift + F2 or by executing the menu command Development → Development Panel... Enter the following in the command line at the bottom of the window: media emulate print, ending with Enter... The active tab will act as if for it media type would print until you close or refresh the page.

Firefox print emulation

Chrome also has a similar feature. Open up Developer tools, for which, in MacOS, you can use the keyboard shortcut CMD + Opt + I, v Windows - Ctrl + Shift + I, or execute the menu command Additional Tools -> Developer Tools... After that open the render panel. One way to do this is to press the key Esc, display the panel Console, and then, through the menu, open the panel Rendering... In the rendering panel, set the flag Emulate CSS Media and select Print.


Chrome print emulation

You can read more about testing print web pages on StackOverflow.

3. Absolute units

Absolute units are not very suitable for on-screen versions of pages, but for printing they are just what you need. It is completely safe for printing styles, moreover, it is recommended to use absolute units of measurement, like cm, mm, in, pt, or pc.

Section (margin-bottom: 2cm;)

4. Properties of pages

You can use the @page rule to control page properties, such as page sizes, orientations, and margins. This turns out to be very useful, for example, when it is necessary that all printed pages have the same margins.

@media print (@page (margin: 1cm;))
The @page rule is part of the Paged Media Module standard, which offers many great things like choosing the first page to print, setting blank pages, positioning elements at the corners of the page, and. It can even be used to prepare a book for printing.

5. Controlling page breaks

Since printed sheets, unlike web pages, are not endless, the content of web pages sooner or later breaks off on one sheet of paper and continues on the next. There are five properties to control page breaks.

▍Page break before element

If you want an element to always be at the beginning of the page, you can put a forced page break in front of it using the page-break-before property.

Section (page-break-before: always;)

▍Page break after element

The page-break-after property allows you to set a forced page break after an element. Using this property, you can also deny the break.

H2 (page-break-after: always;)

▍ Page break inside element

The page-break-inside property comes in handy when you want to avoid splitting an element between two pages.

Ul (page-break-inside: avoid;)

▍ Top and Bottom Hanging Rows

Sometimes you don't need to force page breaks, but you want to control the output of paragraphs at page boundaries.

For example, if the last line of a paragraph does not fit on the current page, the last two lines of that paragraph will be printed on the next page. This is due to the fact that the property that controls it (widows, that is - "top orphans") is set to 2 by default. This can be changed.

P (widows: 4;)
If a different situation arises and only one line of a paragraph fits on the current page, the entire paragraph will be printed on the next page. The orphans property is also set to 2 by default.

P (orphans: 3;)
The point of the above code is that in order for a paragraph not to wrap entirely on the next page, at least three lines must fit on the current page.

For a better understanding of this, take a look at an example prepared with CodePen. And here is a debug version of the same example, it is more convenient to test it.

*, *: before, *: after, *: first-letter, p: first-line, div: first-line, blockquote: first-line, li: first-line (background: transparent! important; color: # 000 ! important; box-shadow: none! important; text-shadow: none! important;)
By the way, CSS styles for printing are one of the few exceptions where the! Important directive is absolutely fine;)

7. Removing unnecessary content

In order not to waste ink, you should remove everything unnecessary from the printed version of the page, such as huge beautiful slides, advertisements, site navigation tools, and so on. This can be done by setting the display property to none on unnecessary elements. It is quite possible that you will find it correct to show only the main content of the page, and hide everything else:

Body> *: not (main) (display: none;)

8. Output of URLs of links

Links, in the form in which they usually appear on web pages, are completely useless when printed, unless the reader of the paper version of the document knows where they lead.

In order to display the addresses of links after their textual representations, it is enough to use the following style:

A: after (content: "(" attr (href) ")";)
Of course, with this approach, a lot of unnecessary things will be "decoded". For example, relative links, absolute links on the same site as the page being printed, links with anchors, and so on. In order not to clog the printed page, it would be better to use something like this:

A: not (): after (content: "(" attr (href) ")";)
It looks, of course, insane. Therefore, I will explain the meaning of this rule in ordinary language: "Display the value of the href attribute next to every link that has an attribute that starts with http, but does not contain mywebsite.com."

9. Decoding of abbreviations

Abbreviations in the text should be placed in the tag , and their decoding must be included in the title attribute. If you style abbreviations like this, their meanings are very easy to show on a printed page:

Abbr: after (content: "(" attr (title) ")";)

10. Forced background printing

Typically, browsers, when rendering a page for printing, do not display the background color and background images, unless they are explicitly told to do so. However, sometimes it is necessary to print all this. This is where the non-standard print-color-adjust property helps us, which allows us to override the default settings for some browsers.

Header (-webkit-print-color-adjust: exact; print-color-adjust: exact;)

11. Media queries

If you write media queries similar to the one shown below, keep in mind that the CSS rules in such queries will not affect the printed version of the page.

@media screen and (min-width: 48em) (/ * screen only * /)
Why is this so? The point is that CSS rules only apply if the min-width is 48em and if the media-type is screen. If we get rid of the screen keyword in this media query, then it will be limited only by the min-width value.

@media (min-width: 48em) (/ * all media types * /)

12. Printout of maps

Current versions of Firefox and Chrome can print maps, but Safari, for example, cannot. What about printing cards? One of the universal options is to use static maps instead of dynamic ones.

Map (width: 400px; height: 300px; background-image: url ("http://maps.googleapis.com/maps/api/staticmap?center=Wien+Floridsdorf&zoom=13&scale=false&size=400x300&maptype=roadmap&format=png&visual_refresh=true "); -webkit-print-color-adjust: exact; print-color-adjust: exact;)

13. QR codes

Printing QR codes containing important links can greatly improve the usability of hardcopy web pages. Here's The Smashing Magazine for helpful advice on the topic. One of them is to include their addresses in the form of QR codes on printed pages. As a result, the user, in order to open the page from which the printout was made in the browser, does not have to type its full address on the keyboard.

14.About printing unoptimized pages

While getting into the topic of printing web pages, I discovered a great tool that allows you to conveniently prepare non-optimized pages for printing. With Printliminator

Page breaks

The following sections describe the page formatting model used in CSS2. Five different properties are used to tell the user agent where it can or should break the page and the page (left or right) where it should continue to display content. Each page break interrupts the display of content in the current page box and causes the remainder of the document tree to be displayed in a new page box.

Breaks before and after elements: "page-break-before", "page-break-after", "page-break-inside"
"page-break-before"


Initial value: auto
Inheritance: no
Percentage assignment: N / A

"page-break-after"

Value: auto | always | avoid | left | right | inherited
Initial value: auto
Scope: structural level elements
Inheritance: no
Percentage assignment: N / A
Devices: visual formatting, paginated

"page-break-inside"

Value: avoid | auto | inherited
Initial value: auto
Scope: structural level elements
Inheritance: yes
Percentage assignment: N / A
Devices: visual formatting, paginated

The values ​​of these properties have the following meanings:

auto

Does not initiate or disallow a page break before (after or within) a generated block.

always

Always initiates a page break before (after) the generated block.

avoid

Cancels the page break before (after or inside) the generated block.

left

Initiates one or two page breaks before (after) the generated block, so that the next page is formatted as the left page.

right

Initiates one or two page breaks before (after) the generated block so that the next page is formatted as the right page.

The potential location of a page break is determined by the "page-break-inside" property of the parent element, the "page-break-after" property of the preceding element, and the "page-break-before" property of the subsequent element. If the values ​​of these properties are other than "auto", then the values ​​"always", "left", and "right" take precedence over the value of "avoid". The section on acceptable page breaks provides clear rules for initiating or disallowing page breaks using these properties.

Using named pages: "page"
"page"

Meaning:<идентификатор>| auto
Initial value: auto
Scope: structural level elements
Inheritance: yes
Percentage assignment: N / A
Devices: visual formatting, paginated

The "page" property can be used to determine the specific type of page on which the element will be displayed.

In this example, all tables will be placed on the right side of the page (called "rotated"), which is in landscape orientation:


TABLE (page: rotated; page-break-before: right)

The action of the "page" property is as follows: if the value of the "page" property of a page block, the content of which belongs to the inline level, differs from the value of a similar property of the previous page block, the content of which also belongs to the inline level, then one or two page breaks are inserted between them, after which the output is made in a named page block. See the section below on forced page breaks.

In the following example, two tables are displayed on landscape pages (naturally on the same page if they both fit on it), the page type "narrow" is not used at all, even though it is set for the DIV element.

@page narrow (size: 9cm 18cm)
@page rotated (size: landscape)
DIV (page: narrow)
TABLE (page: rotated)

used in document


...

...

Page breaks within elements: "orphans", "widows"
"orphans"

Meaning:<целое>| inherited
Initial value: 2
Scope: structural level elements
Inheritance: yes
Percentage assignment: N / A
Devices: visual formatting, paginated

"widows"

Meaning:<целое>| inherited
Initial value: 2
Scope: structural level elements
Inheritance: yes
Percentage assignment: N / A
Devices: visual formatting, paginated

The orphans property determines the minimum number of paragraph lines that should be left at the bottom of the page. The "widows" property determines the minimum number of paragraph lines that should be left at the top of the page. Examples of using these properties to control page breaks are given below.

For more information on formatting paragraphs, see the section on line boxes.

Acceptable page breaks

In normal flow, the page break can be in the following locations:

  1. In the space reserved for vertical margins between building blocks. If a page break occurs at this point, then the computed values ​​of the corresponding "margin-top" and "margin-bottom" properties are set to "0".
  2. Between line blocks within a structural level block.

Discontinuities of the considered type satisfy the following rules:

  • Rule A: Break (1) is allowed only if the values ​​of the "page-break-after" and "page-break-before" properties of all the elements that spawn blocks that occur at the break are allowed to occur, which occurs when at least one of them is "always", "left" or "right", or all of them are "auto" at the same time.
  • Rule B: However, if all of these properties are set to "auto" and the "page-break-inside" property of the closest common ancestor of all named elements is set to "avoid", then a page break at that point is prohibited.
  • Rule B: Page break (2) is allowed only if the number of line boxes between the break and the beginning of the closing block is equal to or greater than the value of the "orphans" property, and the number of inline boxes between the break and the end of the block is equal to or greater than the value of the "widows" property ...
  • Rule D: Moreover, page break (2) is allowed only if the "page-break-inside" property is set to "auto".

If the rules above do not allow you to insert enough breaks, then rules B and D are ignored to prevent content flowing out of the page block, which allows you to create additional breaks.

If after this it is not possible to achieve a sufficient number of breaks, then rules A and B are not taken into account to search for additional break points.

Page breaks cannot be made in absolutely positioned blocks.

Forced page breaks

A page break must occur (1) if at least one of all the "page-break-after" and "page-break-before" properties of the elements that generate blocks that occur at the break point is "always", "left", or "right".

A page break must also occur (1) if the values ​​of the "page" property of the line boxes immediately before and after the break are different.

"Best" page breaks

CSS2 does not specify which page break of the many allowed breaks should be used; CSS2 does not prevent user agents from inserting page breaks anywhere or not using them at all. But the CSS2 spec strongly recommends that user agents adhere to the following heuristics (until it appears that they sometimes contradict each other):

  • page breaks should be done as seldom as possible;
  • all pages that do not end with a forced break should be approximately the same height;
  • there should be no breaks inside a block that has a border;
  • there should be no breaks inside the table;
  • there should be no gaps inside the moved object.

Suppose your style sheet contains the properties "orphans: 4" and "widows: 2" and there are 20 rows (line boxes) available at the bottom of the current page:

  • if the last paragraph of the current page contains no more than 20 lines, then it must remain on the current page;
  • if the paragraph contains 21 or 22 lines, and the second part of the paragraph should not violate the restrictions set by the "widows" property, then, by virtue of this, its second part should consist of two lines;
  • if a paragraph has more than 23 lines, then the first part should be 20 lines long, and the second part should include all other lines.

Now, suppose the value of the "orphans" property is "10", the value of the "widows" property is "20", and there are 8 rows available at the bottom of the current page:

  • if the paragraph at the end of the current page contains no more than 8 lines, then it must remain on the current page;
  • if a paragraph contains more than 9 lines, then it cannot be divided (since this will violate the restriction set by the "orphans" property). Therefore, it should be moved to the next page as a block.


How to deal with page breaks when printing a large HTML table (8)

I have a project that requires printing an HTML table with many rows.

My problem is how the table is printed across multiple pages. It sometimes cuts the line in half, making it unreadable because one half is on the edge of the page and the rest is printed at the top of the next page.

The only plausible solution I can think of is to use complex DIVs instead of a table and force page breaks if needed ... but before going through all the changes I thought I might ask here earlier.

Use these CSS properties:

Page-break-after page-break-before

For example:

....

None of the answers here worked for me in Chrome. AAverin on GitHub created some useful Javascript for this and this worked for me:

Just add js to your code and add the splitForPrint class to the table and it will neatly split the table into multiple pages and add the table header to each page.

Note: when using a page break: always for a tag, it creates a page break after the last bit of the table, creating a completely blank page every time! To fix this, just change it to page-break-after: auto. It will break correctly and won't create an extra blank page.

....

The accepted answer didn't work for me in all browsers, but after the css actually worked for me:

Tr (display: table-row-group; page-break-inside: avoid; page-break-after: auto;)

The html structure was:

...

In my case, there were some additional problems with thead tr, but this solved the original problem of holding table rows.

Due to header issues, I ended up ending up with:

#theTable td * (page-break-inside: avoid;)

This did not stop the ranks from breaking down; only the contents of each cell.

I ended up with @ vicenteherrera's approach, with some tweaks (which is perhaps bootstrap 3).

Basically; we cannot break tr s or td s because they are not block level elements. So we insert div s into each one and apply our page-break- * rules to the divs. Second, we add some padding to the top of each of these divs to compensate for any styling artifacts.

Tweaks and padding adjustments were needed to compensate for some of the jitter that was being introduced (from bootstrap, I guess). I'm not sure if I am presenting a new solution from other answers to this question, but maybe it will help someone.

I recently solved this problem with a nice solution.

AvoidBreak (border: 2px solid; page-break-inside: avoid;)

Function Print () ($ (". TableToPrint td, .tableToPrint th"). Each (function () ($ (this) .css ("width", $ (this) .width () + "px"))) ; $ (". tableToPrint tr"). wrap ("

"); window.print ();)

Works like a charm!

I have tested many solutions and none worked well.

So I tried a little trick and it works:

tfoot with style: position: fixed; bottom: 0px; position: fixed; bottom: 0px; fits at the bottom of the last page, but if the footer is too high, it overlaps with the contents of the table.

tfoot only with: display: table-footer-group; does not overlap but is not at the bottom of the last page ...

Let's put two tfoots:

TFOOT.placer (display: table-footer-group; height: 130px;) TFOOT.contenter (display: table-footer-group; position: fixed; bottom: 0px; height: 130px;) your long text or high image here

One reserves space on non-back pages, the other in your personal footer.

Test

heading
notes
x
x
x


Although we live in a digital age where everything can be easily accessed, there are still many people who prefer to read long text off paper. There is a chance that some users will print out the text from your site so that they can read it outside the computer.

The ability to render content suitable for printing has been around for a long time. We can do this using the @media rule in the stylesheet like this:

@media print ( / * Style rules * / }

There are several properties that allow you to style the content of a web page to render it printable, and we'll cover one: page break.

What does it do?

If you've worked with text editors such as Microsoft Word and Pages, you should be familiar with the page break menu that lets you wrap text on the next page.

This module does the same, allowing you to control how the content of a web page is wrapped, page by page.

Using a page break

As an example, we have created a demo page that we are going to print. We found a bad transfer on it, as you can see below.

It will look better if the heading and the orphaned line start on the next page.

To do this, we use the page-break-after property and set it to always to force the next element to go to the next page.

Page-break (page-break-after: always;)

Then you can create a new element with a class between the elements, or assign the class to the previous element in this way.

With the Eraser feature, you can take composites of a photo, then put all of that together, to get the background without the extras you don’t.

The phone to travel With

S Translator is going to be a great tool for your travels as ...

Now the heading and the bottom hanging line will start on the next page.

Top and bottom dangling lines

The above method can be tedious if you have a lot of text. So instead of forcing the content to go to the next page, it’s better to set a minimum threshold for the top and bottom orphans.

In typographic practice, top and bottom hanging lines refer to leftover words and short lines that appear torn off from the rest of the paragraph on another page.

Using the properties orphans (bottom orphans) and widows (top orphans) we can set the minimum threshold. In the example below, we are specifying that at least three lines remain at the bottom or at the beginning of the paragraph where the page break occurs.

P (orphans: 3; widows: 3;)

Additional sources

We've covered the basics of using a printable page break for text on your site, and we hope that it will inspire you to think about styles for your site to print so that your content looks good both on screen and on paper.

Translation - Duty

A page block consists of a page area that contains content and a margin area that surrounds the page area. The @page rule is used to change some css properties when printing a document. You can only change the margins of the element, and you can also set page breaks at a specified location.

@page (margin: 2in;)

It is possible to define individual document margins within the @page rule, such as margin-top, margin-right, margin-bottom, margin-left:

2. Page breaks

You can control page breaks using the page-break-before, page-break-after, and page-break-inside properties. These properties apply to block elements for which the position property is set to relative or static.

page-break-before
Values:
auto
always Always adds a page break before the element.
avoid Cancels the placement of the break in front of the element, if possible.
left Adds one or two page breaks before the element so that the next page is formatted as the left page. The element will be printed starting from the top of the left page, i.e. on the page to the left of the spine. For duplex printing, will be output on the back of a sheet of paper.
right Adds one or two page breaks before the element. The element will be printed starting at the top of the right border. The next page will be formatted as the right page.
inherit

Syntax:

@media print (h1 (page-break-before: always;))

page-break-after
Values:
auto The default is to set automatic page breaks.
always Always adds a page break after an element.
avoid Cancels the addition of a break after the element, if possible.
left Adds one or two page breaks after the element so that the next page is formatted as the left page. The element will be printed starting from the top of the left page, i.e. on the page to the left of the spine. For duplex printing, will be output on the back of a sheet of paper.
right Adds one or two page breaks after the element so that the next page is formatted as the right page. The element will be printed starting at the top of the right border.
inherit Inherits this property from the parent element.

Syntax:

@media print (footer (page-break-after: always;))

The page-break-inside property tells the browser whether the page can break inside the element or not. But if the element is longer than the page, then the break is inevitable.