Search code examples
python-sphinxrestructuredtext

Align leged text in figure caption Sphinx


I cannot choose to align the legend text of a figure in sphinx.

.. figure:: check_validity.png
   :align: center

   ..

   Left: the source layer

   Right: in blue the valid layer, in green the invalid layer and in red the error
   layer

This the result:

enter image description here

But I would like to have both caption aligned left. Is this possible without using tables?


Solution

  • Yes, but it is very kludgy, requiring custom CSS to account for each image's width.

    Here's the HTML that Sphinx generates for me:

    <div class="figure align-center">
        <img src="check_validity.png" />
        <div class="legend">
            <p>Some text</p>
            <p>Another sentence</p>
        </div>
    </div>
    

    Depending on your theme, you would need to:

    1. get the width of the image (WI)
    2. get the width of the content area (WCA), which might be impossible if it is a fluid, variable width area
    3. calculate the left margin: LM = (WCA - WI)/2
    4. apply LM as the left margin to the paragraph block with a CSS selector

    It's far easier to just use tables. Welcome to the 1990s!

    Here's the reST markup:

    .. rst-class:: table-center
    
    +--------------------------------+
    | .. figure:: check_validity.png |
    |                                |
    |   ..                           |
    |                                |
    |   Left: the source layer       |
    |                                |
    |   Right: in blue the valid     |
    |   layer, in green the invalid  |
    |   layer and in red the error   |
    |   layer                        |
    +--------------------------------+
    

    And you will need to add a custom style to your CSS file:

    table.table-center {
        margin-left: auto;
        margin-right: auto;
    }