Page counters

Print-CSS defines two special counters, page and pages, which can be used to display the current page number and the total number of pages, respectively. For example, the following code will display the current and total page numbers at the bottom right of each page:

@page {
    size: A4;
    margin: 20mm;

    @bottom-right {
        content: 'Page: ' counter(page) ' of ' counter(pages);
        font-size: 0.7em;
    }
}

Manipulating the page counter

The page and pages counters can both be manipulated, but only within the @page at-rule context. For instance, in the following example, the first page is a cover page, so it is not included in the page numbering. To achieve this, we reset the page and pages counters to -1 so that they will start counting from the beginning on the next page:

@page:first {
    size: A4;
    counter-reset: page -1 pages -1;
    @bottom-right {
        content: none;
    }
}

Keep in mind that these counters can only be manipulated within the @page at-rule context.

Target page counter

You can use the target-counter function to retrieve the page number of an element and display it as part of your content. A common use case for this is creating a table of contents (TOC).

Here is an example of how you can use the target-counter function to retrieve the page number for the element that a link (specified by the href attribute) points to:

#toc a::after {
    content: ' (' target-counter(attr(href url), page) ')';
}
HTML table of content code
<ol id="toc">
    <li><a href="#topic-1">Lorem ipsum dolor</a></li>
    <li><a href="#topic2-">Stet clita kasd</a></li>
</ol>

Last updated