CodeBlanks Logo Icon CodeBlanks

Page number

CSS course · Advanced · Lesson 41/52

Learn to add page numbers with CSS.

Page number counters

To show each page's number when printing, CSS counters help. The counter(page) expression gives the current page number. It goes inside the content property of a margin box within @page.

Example: @page { @bottom-center { content: counter(page); } }. This writes the number at the bottom center of each page. Other boxes include @bottom-left and @top-right.

Page number formats

You can display the page number in other formats. counter(page, upper-roman) uses capital Roman numerals (I, II, III). counter(page, lower-alpha) uses letters (a, b, c).

You can also join two counters: content: "Page " counter(page). The footer then reads "Page 1", "Page 2", and so on. Format the content however you like.

Exercise Put the page number at bottom center

Write an @page declaration. Inside it, define a @bottom-center box with content: counter(page). The same @page block must also declare margin: 2cm.

Show example solution
/* put page number at bottom center */
@page {
  margin: 2cm;
  @bottom-center {
    content: counter(page);
  }
}

Test yourself

  1. What does counter(page) give?

    @page { @bottom-center { content: counter(page); } }
    • Total element count
    • Page margin
    • Print date
    • Current page number
    Show answer

    Current page number — Correct. counter(page) gives the current page number.

  2. Put the page number at bottom center

    @page {
      @bottom-center {
        content: ____;
      }
    }
    Show answer
    @page {
      @bottom-center {
        content: counter(page);
      }
    }
  3. What does counter-reset: page do?

    h1 { counter-reset: page; }
    • Restarts the counter at zero
    • Decreases the counter by one
    • Deletes the counter
    • Hides the counter
    Show answer

    Restarts the counter at zero — Correct. counter-reset: page restarts the counter at zero.

  4. Match each piece to its meaning

    counter(page)
    Page number
    counter-reset
    Restart counter
    @bottom-center
    Bottom center box

All lessons in Advanced