python-sphinxrestructuredtext

Add CSS class to Sphinx-generated anchor span


With this RST file:

.. cssclass:: myclass
.. _important:

Something really important
--------------------------

...and this call:

sphinx-build -C ./ ./html ./index.rst

...the following HTML results:

<section class="myclass" id="something-really-important">
  <span id="important"></span>
  <h1>Something really important</h1>
</section>

It would be really convenient for me if Sphinx could place the class="myclass" into the span element, instead of into the section element.

Is that possible?


Solution

  • There is no reStructuredText syntax or Docutils/Sphinx setting that allows to add a custom class on the auxiliary span holding an alias ID.


    This span is added by the HTML writer component because the section has two IDs: the auto-generated "something-really-important" and the ID set by the internal hyperlink target .. _important:. The Docutils native XML would look like

        <target refid="important"></target>
        <section classes="myclass" ids="something-really-important important" names="something\ really\ important important">
            <title>Something really important</title>
        </section>
    

    but HTML does not support more than one ID per element, so a workaround is required.