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 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

Web Dev

Creating Docker images with M1 Macs

I ran into an issue with my Dockerfile when using it on a Linux machine, setting a platform fixed the issue

Web Dev

What does --no-owner mean in Postgres?

You have read a guide to doing Postgres exports or imports and seen --no-owner, this is what it means