pythonjupyter-notebookoutputword-wrap

How to disable line wrapping in Jupyter notebook output cells?


By default longer lines of text in the output cells of a Jupyter notebook will be wrapped. How to stop this behaviour?


Solution

  • I was able to solve this problem by adding a simple CSS rule to the custom/custom.css file in my Jupyter user configuration:

    /*Disable code output line wrapping*/
    div.output_area pre {
        white-space: pre;
    }
    

    The result:

    enter image description here

    The div.output_area pre selects the pre preformated text areas of the code output areas for the rule (set of css properties). The white-space property states how the browser should display white spaces in the selected HTML elements with the pre value the browser only breaks at new line characters \n and <br> elements.

    This CSS renders well (with a fine horizontal scrollbar) for my Firefox v70.0 and Chorme v78.0.3904.97, according to Can I Use the white-space: pre property and value should work on all modern desktop browsers.

    You can find out where your configuration resides by running the following shell command:

    jupyter --config
    

    If you want make further style modifications just play around with the inspector of your favorite browser on Jupyter Notebook tab. where you can modify the CSS without permanent effects.

    Update for JupyterLab

    As kiesel commented: In JupyterLab the class of the parent div is changed to jp-OutputArea-output. However there is another problem: Jupyter Lab does not read the custom/custom.css file. There is two way around this.

    1. (dirty, fast) edit the theme in use.

    In my case I edited the ~/miniconda3/envs/< env name >/share/jupyter/lab/themes/@jupyterlab/theme-dark-extension/index.css file and added the following code.

    div.jp-OutputArea-output pre {
        white-space: pre
    }
    

    of course this fix will only work in the one specific environment where you edited the theme index.css. Therefore I do not recommend it.

    2. (clean, slow) Use an extension which supports custom CSS

    This nice fellow made a theme for Jupyter Lab which allows you to include a custom CSS file.