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

Ruby

Forcing a Rails database column to be not null

How you can force a table column to always have something in it with Rails

Writing Marketing

We've deleted an article's worth of unhelpful words

We've improved several pages across our site by removing words that add no value, and often detract from the article.