You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CSS打印媒体中计数器不递增,无法实现每页带页码页脚的问题求助

CSS打印媒体中计数器不递增,无法实现每页带页码页脚的问题求助

我最近在做网页打印的页码功能,想给每一页的页脚加上正确的页码,但CSS里的counter-increment怎么都不生效,打印预览里所有页面的页码都是一样的,实在卡壳了,来求助大家!

我最初写的代码片段如下:

<head>
  <style>
    @media print {
      body {
        counter-reset: page-num;
      }
      footer .count-page-num::before {
        counter-increment: page-num;
      }
      footer .count-page-num::after {
        content: "Page " counter(page-num);
      }
      header {
        font-size: x-small;
        position: fixed; /* always print the headers*/
        left: 0;
        right: 0;
        top: 0;
        border-bottom: 1px solid #444;
      }
      footer {
        font-size: x-small;
        position: fixed;
        left: 0;
        right: 0;
        bottom: 0;
        border-top: 3px solid #000;
      }
    }
  </style>
</head>
<body>
  <header></header>
  <div> -- main content here --</div>
  <footer class="page-footer">
    <div> TEST FOOTER </div>
    <div>
      <span class="count-page-num"></span>
    </div>
  </footer>
</body>

后来我还试过另一种写法,但还是不行:

@media print {
  body {
    counter-reset: page-num;
  }
  footer .count-page-num::after {
    content: "Page " counter(page-num);
  }
  page {
    counter-increment: page-num;
  }
}

我查了相关文档和讨论帖,还是没解决问题。我自己猜测,会不会是因为页脚用了position: fixed?毕竟固定定位的元素在页面里只渲染一次,打印的时候每一页都是复用这个元素,所以计数器只在初始化的时候设为0,根本没机会逐页递增。有没有大佬能指点一下该怎么调整呀?

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.07 12:09:28