3

Here is a piece of HTML/CSS code, which should print, thanks to CSS' counters, the page number in footer when printed :

<html>
  <head>
    <style type="text/css">
      body {
        counter-reset: page;
      }
      div.footer {
        display: table-footer-group;
        position: fixed;
        bottom: 0pt;
        right: 0pt;
      }
      div.footer:after {
        counter-increment: page;
        content: "Page " counter(page);
      }
      p {
        page-break-after: always;
      }
    </style>
  </head>
  <body>
    <div class="footer"></div>
    <p>Hello world page 1</p>
    <p>Hello world page 2</p>
  </body>
</html>

The fact is, with Firefox 79.0, I get "Page 1" on first page, and "Page" on second. With Chrome 84.0, I get "Page 1" on both pages.

I tried to use @page at-rule, native "page" counter (as described on w3), I still can't find what I'm missing.

Thanks a lot for your help :)

  • i'm afrais it's a known bug .... You may check on similar question here on SO to find out .. https://stackoverflow.com/questions/50681472/css-counter-increment-page-on-print-view-issue (among other Q/A ) – G-Cyrillus Aug 18 '20 at 19:26

1 Answers1

2

I don't think you can achieve what you're trying to. The reason you get "Page 1" is because you're incrementing the counter inside the div.footer:after declaration, which appears only once in your HTML code.

The CSS counter, when it's read, is calculated based on that element's location in the document, like described in the specs: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Lists_and_Counters/Using_CSS_counters

So in your case, you can think about it like this:

div.footer:after {
  content: "Page " counter(page); /* when displayed, read the value of `page` */
}
p {
  counter-increment: page; /* counter increments with every occurrence of a <p> tag */
}

and

<div class="footer"></div> <!-- `page` counter is always 0, as no occurrences of a <p> tag yet -->
<p>Hello world page 1</p> <!-- sets counter to 1 -->
<p>Hello world page 2</p> <!-- sets counter to 2 -->

or

<p>Hello world page 1</p> <!-- sets counter to 1 -->
<div class="footer"></div> <!-- `page` counter is always 1, as there was a single occurrence of a <p> tag -->
<p>Hello world page 2</p> <!-- sets counter to 2 -->

or

<p>Hello world page 1</p> <!-- sets counter to 1 -->
<p>Hello world page 2</p> <!-- sets counter to 2 -->
<div class="footer"></div> <!-- `page` counter is always 2, as there were two occurrences of a <p> tag -->
Andrei Duca
  • 372
  • 2
  • 11
  • What you probably want to do is have a ` – Andrei Duca Aug 18 '20 at 17:44