Squash br inside contenteditable

This has to go down as one of my favourite little CSS hacks 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

Using the 'it' Gem to add links to translations

How to can use the 'it' Gem to add links to your translations

Slack

Custom Startup Messages on Slack

How to set a custom start up message on your team's Slack channel. Part of our Slack mini series.