Search code examples
python-sphinxrestructuredtext

Applying CSS and roles for text blocks instead of inline spans in Sphinx


There is a previous question that explains how to add a color span to some reStructuredText.

To recap the procedure:

First, you have the role.

.. role:: red

An example of using :red:`interpreted text`

It translates into as follows.

<p>An example of using <span class="red">interpreted text</span></p>

Now, you have the red class, you can use CSS for changing colors.

.red {
    color:red;
}

How do you do this if you want text that spans multiple lines? For example:

.. role:: red

:red:`paragraph 1

      paragraph 2

      paragraph 3`

Where paragraph 1, 2, & 3 would all be "red". If I try to do this I get the warning message:

WARNING: Inline interpreted text or phrase reference start-string without end-string.

It doesn't create the span and inserts ":red:" into the text. It just doesn't interpret this as a string (as the warning suggests).

Basically, can this be done in reStructuredText, and if it can, how?

I'm using Sphinx 1.1.3.


Solution

  • There are a number of ways to do this, but one of them is to use the class directive:

    .. class:: red
    
        This is a paragraph.
    
        This is another paragraph.
    

    Most docutils HTML writers will put that into html output as a class html attribute, which you can then style with CSS.

    In Sphinx, in particular, however, you may need to use rst-class instead of class in at least some cases. See: https://www.sphinx-doc.org/en/2.0/usage/restructuredtext/basics.html

    Also, many block-level elements in RestructuredText take a :class: parameter which does pretty much the same thing.