2

Problem summary

I'm creating a print stylesheet for a simple html document with id-referenced headers and anchors to reference these headers, like

<h1 id="the-document">The Document</h1>
<h2 id="background">Background</h2>
<h2 id="implementation">Implementation</h2>
<p>For details, see <a href="#background">Background</a>.</p>

The print styles need section numbers that are created with css counters like

h1 {
  counter-reset: section
}
h2:before {
  content: counter(section) ". ";
  counter-increment: section
}

I try to add the "1. " that is prepended to the "Background" section also to the anchor that references the section, i.e. the result should look like

The Document

1. Background

2. Implementation

For details, see 1. Background

Is there a way to add the counter of the section that is referenced to the anchor that references the section? Without JavaScript?

What I've tried

Adding the current counter to all references results in the wrong counter value, like

a[href^=#]:before { content: counter(section) ". "; }

would result in

For details, see 2. Background

I know this could be done with JavaScript:

let section = 0;
const h2s = Array.from(document.querySelectorAll('h1, h2')).reduce((h2s, h, i) => {
  switch (h.nodeName) {
    case 'H1': section = 0; break;
    case 'H2': h2s[h.id] = ++section; break;
  }
  
  return h2s;
}, {})

Array.from(document.querySelectorAll('a[href^="#"]')).forEach(_ => _.textContent = `${h2s[_.href.split('#')[1]]}. ${_.textContent}`)
h1 {
  counter-reset: section;
}
h2:before {
  content: counter(section) ". ";
  counter-increment: section;
}
<h1 id="the-document">The Document</h1>
<h2 id="background">Background</h2>
<h2 id="implementation">Implementation</h2>
<p>For details, see <a href="#background">Background</a></p>

Whom it may concern, I'm authoring markdown in Jekyll (for a GitHub Page, so no plugins) and would rather drop the feature than add JavaScript to implement it.

Dominik Schreiber
  • 2,629
  • 1
  • 23
  • 33
  • 3
    I doubt you will find a CSS only solution. This seems to be a lot of job for CSS especially if you want something geneic (we can only find few hack for some particular cases) – Temani Afif Jan 11 '21 at 09:55

0 Answers0