CSS Page property to add Page numbers

Posted By : Milind Ahuja | 28-Jun-2017

In my recent project, we were required to generate the pdf document from HTML page. There was an requirement that each page bottom right needed to have a number on it. All these things need to be replicated on every page. This is done by using the page counter in CSS, a pre-defined counter which represents the current page number.


The page counter starts at 1 and increments automatically at each new page. The property page-break-before is applied to break the page, it is basically used to indicate if a page break should occur immediately before an specified element and if it is set to always, the page break is applied before every element to start the new element at the topof the fresh page.


Page breaks are usually applied to the printed books or documents. In this case, we are applying in a PDF document. 


To know more about CSS3 page properties, you can refer to the following links:

https://www.w3.org/TR/css3-page/

https://www.w3.org/TR/CSS21/generate.html#counters


Following is the code to display the page numbers at the bottom of each page using above properties.

    .page {
     position: relative;
     height: auto;
     min-height: 750px;
     width: 590px;
     display: block;
     background: rgba(60, 60, 60, 0.28) !important;
     margin: 0 auto 5px;
     page-break-before: always; /*This style rule makes every page element start at the top of a new page:*/
     counter-increment: page
    }
   /*page numbers*/
   div.page:after {
     content: " PAGE - " counter(page);
     position: absolute;
     bottom: 0px;
     right: 15px;
     z-index: 999;
     padding: 2px 12px;
     border-right: 2px solid #23b8e7;
     font-size: 12px;
    }
   

MARKUP :


 

This is Page #1

This is page #2

This is page #3

This is page #4

Hope it helps. THANKS

About Author

Author Image
Milind Ahuja

Milind is a bright Lead Frontend Developer and have knowledge of HTML, CSS, JavaScript, AngularJS, Angular 2+ Versions and photoshop. His hobbies are learning new computer techniques, fitness and interest in different languages.

Request for Proposal

Name is required

Comment is required

Sending message..