How to replace line break tags (<br>) with spaces in CSS

Sep 22, 2020 · by Tim Kamanin

You have a text separated by line break tags <br>, like this:

html
One file only.<br>
50 MB limit.<br>
Allowed types: gif, jpg, png, svg.<br>

And you want to turn the text into a single line, like that:

html
One file only. 50 MB limit. Allowed types: gif, jpg, png, svg.

If you don't have access to the HTML, you might be tempted to reach for JavaScript, but wait, my friend, put that big gun down, you can solve the task with the only CSS!

The trick here is to use the CSS content property.

We will solve it in two steps:

  1. At first, we re-set the content of the line break tag to prevent it from, you guessed it, breaking a line:

    css
    br {
        content: '';
    }
    
  2. And then, we add an empty space after the <br> tag:

    css
    br:after {
        content: ' '; // note we've added space here.
    }
    

Well, it's done! Your line breaks should be replaced with spaces now. In production your styles might look like the following:

css
.flat-breaks br {
    content: '';
}
.flat-breaks br:after {
    content: ' ';
}

As you see, we've nicely scoped the style under .flat-break class, so it's not global and can be used in places where it's really needed.

Want to get more 🔥 tips like this one?

Subscribe to get notified about new dev tutorials