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

MacProductivity

Some Mac Tips

Some settings or tips I've learned over the years to make using your Mac an even nicer experience

Writing Git

How to speed up Rubocop

A small bit of config that could speed up your Rubocop runs