Is it possible to add .css style to Jupyter notebook from separate file?

If you are using Jupyter with Python 3 then there is no urllib2 (it was merged into urllib) and the answers above will give you the error ModuleNotFoundError: No module named 'urllib2'. You may want something like this instead:

from IPython.display import HTML
from urllib.request import urlopen
html = urlopen("[url to your css file here]")
HTML(html.read().decode('utf-8'))

Note that read() returns a bytes encoding, which you must decode if you want text.

If you are using an inline CSS style, you can also pass it as part of the HTML content, for example in a <style> block. Here is a simple example:

from IPython.display import HTML
css_str = '<style>.foo{color:#F00;}</style>'
html_str = '<div class="foo">bar</div>'
html = HTML(css_str + html_str)
display(html)

Output is the word "bar" in red.


If you are okay with the styling applying to all notebooks you make, then you can store your css in ~/.jupyter/custom/custom.css and this will be automatically loaded and will override any default styles.

An alternative is to do something like this:

from IPython.core.display import HTML
import urllib2
HTML(urllib2.urlopen('[url to your css file here').read())

(from http://moderndata.plot.ly/custom-styling-for-ipython-notebooks-with-3-lines-of-code/)

Where you store your css file somewhere (e.g. on Github) and download it and apply it when you run the notebook.

If you want it to be completely external, use custom.css, but this will apply to every notebook. If you need it to only apply to a single notebook, then you'll have to specify it within the notebook, but there are less verbose ways of doing it (like above).

See configuration docs


This answer would probably better be a comment on the earlier answer by Davies and Narasimhan, but I lack the reputation to post a comment.

from IPython.core.display import HTML will work, and was the recommended way to access HTML display capability in earlier versions of IPython. But in recent versions, the public display API is in IPython.display (see its docstring). This module exposes __all__ of IPython.core.display, along with __all__ of IPython.lib.display. Notably, the current IPython docs (The IPython API) don't publicly document IPython.core.display separately. For the current IPython.display docs, see: Module: display — IPython documentation.

So the recommended solution as of IPython 5 I believe would be:

from IPython.display import HTML
import urllib2
HTML(urllib2.urlopen('[url to your css file here').read())