white-space: pre-line converts lines into spaces in Safari when pasting into a textarea

In a site I’m helping with, we encountered this weird behavior: users pasting multiline text into a textarea in Safari (but *not* in Chrome) found their newlines replaced with spaces. This was a problem because lines are used to separate items to be processed. Dropping the lines garbled the meaning of the input.

My first guess was that some errant JavaScript was grabbing the input and transforming it for this particular textarea. Then, however, I found that any textarea in the site was impacted, even a new one added by me. And further, disabling bits of JavaScript (and finally all JavaScript via the Safari developer tools) had no impact.

I was shocked, however, to find that disabling CSS on the page (again via Safari developer tools) fixed the issue. I didn’t know CSS could have that sort of impact. That observation pretty quickly led me to code equivalent to this in one of the stylesheets:

textarea {
  white-space: pre-line;
}

And, sure enough, deleting the line white-space: pre-line; made the issue disappear.

MDN’s description of “pre-line” makes it sound like this behavior is unexpected (at least to me?):

Sequences of white space are collapsed. Lines are broken at newline characters, at <br>, and as necessary to fill line boxes.

Some things I learned from this:

Maybe it’s just because I didn’t hit upon the right search query, but I haven’t found anyone else complaining about this particular issue online. I hope this blog post will help with that. (And if you do find articles talking about it, I’d be interested in hearing about them.)

So, if you’re mystified about newlines disappearing in text pasted into textareas in Safari, look out for white-space: pre-line.

Here’s some example HTML I used to play with this while writing this:

<html>
    <head>
        <title>white-space: pre-line</title>
        <style>
            #text {
                background-color: #eef;
            }
            #white-space-checkbox:checked ~ #text {
                white-space: pre-line;
                background-color: #fee;
            }
        </style>
    </head>
    <body>
        <input type=checkbox id="white-space-checkbox">
        <label for="white-space-checkbox">Use white-space: pre-line</label>
        <br>
        <textarea id=text rows=10 cols=80></textarea>
    </body>
</html>

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *