How to change the background color of a single cell in a jupyter notebook / jupyterlab?

P-Gn picture P-Gn · Mar 22, 2018 · Viewed 13.8k times · Source

I design a notebook so that variables that could be changed by the user are grouped into distinct cells throughout the notebook. I would like to highlight those cells with a different background color so that it is obvious to the user where the knobs are.

How could I achieve that?

NB: This related question was about static code highlighting (for a manual) and the accepted answer proposed to basically put everything in markup comments. In my case, I want highlighted code to be in a runnable cell.

Answer

krassowski picture krassowski · Jun 12, 2018

Here you go (assuming that you use Python kernel):

from IPython.display import HTML, display

def set_background(color):    
    script = (
        "var cell = this.closest('.jp-CodeCell');"
        "var editor = cell.querySelector('.jp-Editor');"
        "editor.style.background='{}';"
        "this.parentNode.removeChild(this)"
    ).format(color)
    
    display(HTML('<img src onerror="{}" style="display:none">'.format(script)))

Then use it like this:

set_background('honeydew')

The solution is a bit hacky, and I would be happy to see a more elegant one. Demo:

enter image description here

Tested in Firefox 60 and Chrome 67 using JupyterLab 0.32.1.

Edit to have it as cell magic, you could simply do:

from IPython.core.magic import register_cell_magic

@register_cell_magic
def background(color, cell):
    set_background(color)
    return eval(cell)

and use it like:

%%background honeydew
my_important_param = 42