14

I am using the following code to insert an image in Jupyter notebook which is compatible with html conversion:

from IPython.display import Image

Image(filename="picture.jpg")

This works nicely except the fact that it is left aligned and I need it centre/middle aligned. Is there any method that I can set it to be aligned correctly?

user2314737
  • 27,088
  • 20
  • 102
  • 114
pouya
  • 141
  • 1
  • 1
  • 5

4 Answers4

19

This works for me:

<center><img src="picture.jpg"/></center>
Steve Roberts
  • 2,701
  • 1
  • 15
  • 9
16

You can set the cell as markdown and use this content:

<img src="picture.jpg" width="240" height="240" align="center"/>

Then run it.

Edit1

Alternatively, you can use a code cell with this code:

from IPython.display import HTML
html1 = '<img src="picture.jpg" width="240" height="240" align="center"/>'
HTML(html1)
swatchai
  • 17,400
  • 3
  • 39
  • 58
6

Many browsers (Chrome, Firefox) are only supporting HTML 5, so this syntax no longer works, even within the notebook itself.

<img src="picture.jpg" align="center"/>

because align="center" has been deprecated. Now you should use CSS style properties and the various margin definitions.

<img src="picture.jpg" style="margin-left:auto; margin-right:auto"/>

or

<img src="picture.jpg" style="margin:auto"/>

See here for more discussion around this. This makes it look properly centered while being displayed in your Notebook. But frustratingly doesn't work (still left justified) when you export your notebook to HTML. Inspecting the HTML that is generated you find that the <img> is embedded in a <p> element and this throws the whole thing off. So you have to add an additional display=block property, making the whole thing

<img src="picture.jpg" style="display=block; margin:auto"/>

This will center the image in your notebook, exported HTML, and exported Markdown files. Thanks to these guys for the tip on the display=block bit.

To get a centered bit of text underneath the image (like a figure title) I throw in a

<p style="text-align: center">
    <b>Figure N. My Cool Figure</b>
</p>

afterwards. The whole setup is then

<img src="picture.jpg" style="display=block; margin:auto"/>
<p style="text-align: center">
    <b>Figure N. My Cool Figure</b>
</p>
Tom Johnson
  • 1,793
  • 1
  • 13
  • 31
0

This is a workaround. i'm using the table syntax on a markdown cell to create a one column table. tables are always aligned in the middle... add your image and use | after it, and - below it. like this:

![Stacklogo](https://stackoverflow.design/assets/img/logos/so/logo-stackoverflow.png) |
-
Ohad
  • 49
  • 1
  • 11