How to set the page-break behavior after an element with JavaScript?

Use the pageBreakAfter property in JavaScript to control page-break behavior after an element. This property is essential for formatting printed documents and print previews.

Note: Changes are only visible when printing the page or viewing print preview (Ctrl+P).

Syntax

element.style.pageBreakAfter = "value";

Property Values

Value Description
auto Default - automatic page breaks
always Forces page break after element
avoid Avoids page break after element
left Forces page break to left page
right Forces page break to right page

Example

The following example demonstrates setting page-break behavior after an element. Click the button and then use Ctrl+P to see the effect in print preview:

<!DOCTYPE html>
<html>
<head>
   <title>Page Break After Example</title>
</head>
<body>
   <h1>Heading 1</h1>
   
   <p>This is the first paragraph with some demo text.</p>
   <p>This is the second paragraph with more content.</p>
   <p id="myFooter">This is footer text that will have a page break after it.</p>
   
   <p>This content will appear on the next page after clicking the button.</p>
   
   <button type="button" onclick="setPageBreak()">Set Page Break After Footer</button>
   <button type="button" onclick="removePageBreak()">Remove Page Break</button>
   
   <script>
      function setPageBreak() {
         document.getElementById("myFooter").style.pageBreakAfter = "always";
         alert("Page break set! Press Ctrl+P to see print preview.");
      }
      
      function removePageBreak() {
         document.getElementById("myFooter").style.pageBreakAfter = "auto";
         alert("Page break removed!");
      }
   </script>
</body>
</html>

How It Works

When you click "Set Page Break After Footer", the JavaScript function applies pageBreakAfter: "always" to the footer element. This forces the browser to start a new page after that element when printing. The "Remove Page Break" button resets it to "auto" for normal flow.

Common Use Cases

  • Separating document sections for printing
  • Ensuring headers appear at page tops
  • Controlling invoice or report layouts
  • Managing multi-page forms

Browser Compatibility

The pageBreakAfter property is supported in all major browsers but only affects printed output, not screen display.

Conclusion

Use pageBreakAfter to control page breaks in printed documents. Set to "always" to force breaks or "avoid" to prevent unwanted breaks between related content.

Updated on: 2026-03-15T23:18:59+05:30

921 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements