Douglas B
Douglas B

Reputation: 832

Maintain image aspect ratio on scaled image with Sphinx/ReStructured Text

I have some documentation built with Sphinx, and I want my scaled images (figures) to behave the same as unscaled figures. For example, a figure declared as

.. figure:: images/manual_exposure1.png

Will display in firefox as a left aligned image with a locked aspect ratio. Resizing the webpage/viewing on mobile work like I expect (the image is scaled down with available space in a locked aspect ratio). If I take the same image and add a scaling factor:

.. figure:: images/manual_exposure1.png
    :scale: 50%

The behavior changes such that the image can become 'squished' if the webpage is resized to certain points. (it will start to squish horizontally while maintaining its height).

I have tried using some custom CSS and have been able to get close to my desired behavior, for instance creating a small css class with a max-width, but that behavior does not match the behavior of the :scale. For instance, the following attempt does scale the images, but also locks it to 50% of the page width, where the :scaled version grows to a maximum size instead, and then can become less % of page width.

.. raw:: html

   <style>
       img.custom-class {
           max-width: 60%;
           height: auto;
           align: left;
       }
   </style>

What's the best way to get unscaled behavior on the scaled images? Should I just rescale the images themselves, or can I do it with sphinx/the right css?

Edit: Adding screenshots demonstrating the behavior at various window widths (widest to narrowest): fullscreen

halfscreen

less than half screen

Upvotes: 3

Views: 50

Answers (1)

G. Milde
G. Milde

Reputation: 929

The "image" directive's scale option sets the <image> Doctree element's "scale" attribute. As there is no direct equivalent in HTML, the HTML writer reads the image size (in px) from the image and writes the scaled values to the output file. Up to Docutils 0.21, the values were written to the HTML <images>s "style" attribute, which overrides styling from a style-sheet. The upcoming Docutils 0.22 will use "height" and "width" attributes to allow combining a configured scale with CSS style rules.

You may try with the development version of Docutils.

Upvotes: 1

Related Questions