CSS to remove document title from Sphinx local ToC#

This week, I’m working on Documatt Sphinx Theme, a theme used for example in this blog. One of the longest postponed feature is displaying a local table of contents (ToC) in the right sidebar. By default, Sphinx displays a current document title in the local ToC, so let’s fix it.

Local ToC is in the most themes displayed in the right side:

Default local ToC#

Sphinx basic theme contains localtoc.html template. Its content in the recent Sphinx version (e.g., 3.5.3) is:

{%- if display_toc %}
  <h3><a href="{{ pathto(master_doc)|e }}">{{ _('Table of Contents') }}</a><h3>
  {{ toc }}
{%- endif %}

As you see, it actually delegate local ToC rendering to the builtin toc variable. It prints local ToC as an unordered list (<ul>) with a single item. The first <li> contains a current document title. The actual local ToC is nested <ul> inside the first item.

<ul>                                      <!-- <1> -->
  <li>                                    <!-- <2> -->
    <a>name of this page</a>              <!-- <3> -->

    <ul>                                  <!-- <4> -->
      <li>... actual toc ...</li>
    </ul>

  </li>
 </ul>

Displaying document title once again is annoying and wasting of valuable space in narrow sidebars:

Fix#

How to remove document title from local ToC? Instead of hacking Sphinx, I decided to hide and fix it with a little (S)CSS.

I overwrite the basic theme’s localtoc.html with my customized version. It changes the label to “On this page” and wraps local ToC to .localtoc:

{%- if display_toc %}
  <div class="localtoc">
    <p class="has-text-weight-bold">{{ _('On this page') }}</p>
    {{ toc }}
  </div>
{%- endif %}

Finally, I used the following (S)CSS to hide and adjust local ToC appearance:

.localtoc {
  &> ul {                                 // <1>
    margin: 0;

    &> li {                               // <2>
      list-style-type: none;

      &> a {                              // <3>
        display: none;
      }

      &> ul {                             // <4>
        // any additional styles to local toc <ul>
        // list-style-type: disc;
        // margin-left: 0.25em;
      }
    }
  }
}

Comments

comments powered by Disqus