Can I display the number of the current page in the content?

Short answer: no.

The current page number can only be displayed inside the header and footer content.

Since header and footer are rendered on top of your Document's content, they have the knowledge of the "current" page. The content on the other hand is not aware of the page it's currently in.

That said, it can still be possible in some cases.

Exception: Powerpoint-like Documents

If you create a Powerpoint-like document where each page is fixed and content doesn't flow from one page to the next, you can use insert the page number using CSS counters.

Let's take the example of a portrait A4 page:

HTML
<div class="page">
  <div>Content of Page 1</div>
  <div class="page-number"></div>
</div>

<div class="page">
  <div>Content of Page 2</div>
  <div class="page-number"></div>
</div>

<div class="page">
  <div>Content of Page 3</div>
  <div class="page-number"></div>
</div>
CSS
/* Initializes a counter named "page" with a value of 0 */
/* Also eliminates any surrounding space to ensure pages are correctly sized */
body {
  counter-reset: page;
  margin: 0;
  padding: 0;
}

/* A portrait A4 page is 793x1120px */
/* Hides any overflow to prevent any print content zoom from happening */
.page {
  height: 1120px;
  overflow: hidden;
  position: relative;
  width: 793px;
}

/* Always positions the page number at the bottom right of the page */
.page-number {
  bottom: 30px;
  position: absolute;
  right: 30px;
  text-align: right;
}

/* Adds 1 to the current value of the "page" counter */
/* Then interts its value inside the .page-number div */
.page-number::before {
  counter-increment: page;
  content: counter(page);
}

Here is what the result will look like.

Why use a CSS counter instead of adding the page number in the content?

You can add the page number in the content if you're sure that the content will never move and if all your pages are fixed.

The CSS counter technique is especially useful if

  • You want the page number to stay consistent even when the actual number of pages changes

  • Some pages are hidden/shown under certain conditions

  • Some pages are generated in a loop

It's just more robust overall and does not require that much more code.

Last updated