Lea Hayes
Lea Hayes

Reputation: 64196

Print page numbers for table of contents using CSS in Chrome

Is there a way to print target page numbers with hyperlinks which linked to various places within the same document?

<h1>Table of Contents</h1>
<ul>
    <li><a href="#introduction">Introduction</a></li>
</ul>

...

<section id="introduction"> <!-- Appears, for example, on page 3 when printed -->
    <h1>Introduction</h1>
    ...
</section>

So that the output is like:

Table of Contents (page 0)

Introduction.........................3


...


Introduction (page 3)

I only need this to work with the Google Chrome browser when printing to PDF (on OS X).

Is there some CSS or JavaScript trickery which would allow me to achieve this?

Upvotes: 11

Views: 9210

Answers (2)

Lea Hayes
Lea Hayes

Reputation: 64196

It looks like this is part of a new working draft of the CSS specification:

http://www.w3.org/TR/2014/WD-css-gcpm-3-20140513/#cross-references

I doubt that there is any browser support yet...

Upvotes: 6

Blake Mann
Blake Mann

Reputation: 5490

I have no idea if this will work in a PDF or not, but to answer the question of how this can be done in CSS:

You can generate the numbers using counter-increment on a pseudo element in css:

note that I changed your <ul> to an <ol> as this is an ordered list, whether you use the list-style or not.

ol {
    counter-reset: list-counter;
}
li:after {
    counter-increment: list-counter;
    content: counter(list-counter);
    float: right;
}

Making the little dotted line in between the text and the number takes a little more work, but you can achieve that by adding in some extra span elements and using css display: table; and display: table-cell; to lay them out properly:

<ol>
    <li><span>Test</span><span class="line"></span></li>
    <li><span>Test2</span><span class="line"></span></li>
    <li><span>Test3</span><span class="line"></span></li>
</ol>

li {
    display: table;
}
li span, li:after {
    display: table-cell;
    vertical-align: bottom;
}
li span.line {
    border-bottom: 1px dotted #000;
    width: 100%;
}

Setting the width to 100% on the span.line element, while not setting any width at all forces it to fill all of the remaining space (this is due to table-cell display elements not being allowed to break to new lines, and preventing overflow of content)

See full demo

It's not the cleanest approach to have to add the extra span elements, but it is a bit of a tricky task. Perhaps someone else will be able to take the time to think of a more efficient way to accomplish it? You could always just put an underline under the entire <li>, and skip the extra markup, at the cost of being a little less cool.

Upvotes: 2

Related Questions