Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS - How to count total number of pages?

I'm trying to show the number of pages on PDF file.

So in the header I put this css:

.page-number:after { 
  counter-increment: pages; 
  content: counter(page) " of " counter(pages); 
 }

Html:

<span class="page-number">Page </span>

But it returns me Page 1 of 1 ... Page 2 of 2. The first counter works fine but the total is wrong. How can I solve that?

like image 934
user3242861 Avatar asked Mar 16 '18 09:03

user3242861


People also ask

How to get total page in CSS?

There is no way to get a counter total with CSS counters so the only way I can think of getting the output you require is to duplicate the HTML (which may not be a big problem if the content is dynamically generated). Output the HTML once to get the total number of pages then again to get the current page.

What is counter-reset in CSS?

The counter-reset CSS property resets a CSS counter to a given value. This property will create a new counter or reversed counter with the given name on the specified element. Normal counters have a default initial value of 0.


1 Answers

There is no way to get a counter total with CSS counters so the only way I can think of getting the output you require is to duplicate the HTML (which may not be a big problem if the content is dynamically generated). Output the HTML once to get the total number of pages then again to get the current page.

#pageCounter {
  counter-reset: pageTotal;
}
#pageCounter span {
  counter-increment: pageTotal; 
}
#pageNumbers {
  counter-reset: currentPage;
}
#pageNumbers div:before { 
  counter-increment: currentPage; 
  content: "Page " counter(currentPage) " of "; 
}
#pageNumbers div:after { 
  content: counter(pageTotal); 
}
<div id="pageCounter">
  <span></span>
  <span></span>
  <span></span>
  <span></span>
</div>
<div id="pageNumbers">
  <div class="page-number"></div>
  <div class="page-number"></div>
  <div class="page-number"></div>
  <div class="page-number"></div>
</div>
like image 193
Hidden Hobbes Avatar answered Oct 28 '22 05:10

Hidden Hobbes