Search code examples
python-sphinxrestructuredtext

:align: image without text wrapping


How can I align an image but without text wrapping around it? One way is to remove

.figure.align-left {float: left;}

from CSS, but this might break other things - anything cleaner in RST (I'm aware of .. raw::html)? Example case, wrapping in Firefox:

Don't wrap me
-------------

.. figure:: img.png
  :align: left
  :width: 500px

or me

Solution

  • Sphinx has a special directive, class, that assigns a CSS class attribute to the next element. Details of how that works is in the docutils documentation of class.

    However in Sphinx, when the default domain contains a class directive, this directive will be shadowed. Therefore, Sphinx re-exports it as rst-class (see note). As a result you must use that in Python because its language uses class.

    The following reStructuredText markup:

    .. rst-class:: image-no-text-wrap
    
    .. figure:: img.png
        :align: left
        :width: 500px
    

    This will yield something like the following HTML:

    <figure class="image-no-text-wrap align-left">
    <a class="reference internal image-reference" href="_images/img.png"><img alt="_images/img.png" src="_images/img.png" style="width: 500px;"></a>
    </figure>
    

    Finally define the CSS selector however you think best to prevent text wrapping, for example:

    figure.image-no-text-wrap {
      overflow: hidden;
      white-space: nowrap;
    }