Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Usage of page-break-before, page-break-after, and page-break-inside properties in CSS
CSS provides three properties to control page breaks when printing documents: page-break-before, page-break-after, and page-break-inside. These properties help you manage how content flows across printed pages, ensuring proper layout and avoiding unwanted breaks.
Syntax
selector {
page-break-before: value;
page-break-after: value;
page-break-inside: value;
}
Possible Values
| Property | Values | Description |
|---|---|---|
page-break-before |
auto | always | avoid | left | right |
Controls page break before element |
page-break-after |
auto | always | avoid | left | right |
Controls page break after element |
page-break-inside |
auto | avoid |
Controls page break inside element |
Example: Chapter Layout with Page Breaks
Suppose your document has level-1 headers that start new chapters and level-2 headers for sections. You want each chapter to start on a new right-hand page, but prevent section headers from being split from their content −
<!DOCTYPE html>
<html>
<head>
<style>
h1 {
page-break-before: right;
color: #2c3e50;
font-size: 2em;
margin: 20px 0;
}
h2 {
page-break-after: avoid;
color: #34495e;
font-size: 1.5em;
margin: 15px 0 5px 0;
}
p {
margin: 10px 0;
line-height: 1.5;
}
</style>
</head>
<body>
<h1>Chapter 1: Introduction</h1>
<p>This chapter introduces the basic concepts...</p>
<h2>Section 1.1: Overview</h2>
<p>This section provides an overview of the topic...</p>
<h1>Chapter 2: Advanced Topics</h1>
<p>This chapter covers advanced concepts...</p>
</body>
</html>
When printed, Chapter 1 starts on a right-hand page, and Section 1.1 header stays with its content. Chapter 2 also starts on a new right-hand page.
Example: Preventing Table Breaks
Use page-break-inside: avoid to keep tables intact across pages −
<!DOCTYPE html>
<html>
<head>
<style>
table {
page-break-inside: avoid;
border-collapse: collapse;
width: 100%;
margin: 20px 0;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}
th {
background-color: #f2f2f2;
}
</style>
</head>
<body>
<h2>Sales Data</h2>
<table>
<tr>
<th>Product</th>
<th>Sales</th>
<th>Revenue</th>
</tr>
<tr>
<td>Product A</td>
<td>150</td>
<td>$15,000</td>
</tr>
<tr>
<td>Product B</td>
<td>200</td>
<td>$25,000</td>
</tr>
</table>
</body>
</html>
When printed, the table will not be broken across pages if possible, keeping all rows together for better readability.
Conclusion
Page break properties are essential for controlling print layout. Use page-break-before and page-break-after to control breaks around elements, and page-break-inside: avoid to keep content like tables intact across pages.
