Squash br inside contenteditable

A fun CSS hack I recently discovered that I thought I'd share

This has to go down as one of my favourite little CSS tricks of late.

I am not a big fan of contenteditable. I think it has a use but it is too easy to misuse and we end up using it for things that input type='text' was really meant for.

One thing that contenteditable does by default which isn’t ideal in most situations is that it allows a carriage return to create a <br /> inside the element marked as contenteditable.

Now you are smart people so you are only grabbing the text from inside the contenteditable element when it comes to saving that data somewhere, so the <br /> won’t persist. Still until the page/data refresh it looks pretty ugly.

Enter CSS

This is such a simple hack, which I think is why I love it;

HTML

<div class="div_that_thinks_it_is_input" contenteditable="true"></div>

CSS

.div_that_thinks_it_is_input br { display: none }

We just don’t display the <br />, no need to get JavaScript to try and parse it out, no need to listen to keyPresses to try and stop it from ever appearing.

If you want a more generalised form of this you can always do;

[contenteditable="true"] br { display: none }

Recent posts View all

Web DevProductivity

Keeping on top of website updates

Learn what website updates are, what they entail, why they are important, and how we can help

Freelancing

Getting the most out of your agency

Here are some tips based on years of working with, for, and as an agency on how to get the most out of any work you do.