Search code examples
htmlcssnewline

CSS white-space pre-wrap rules for lone carriage return


Is it valid to put lone carriage-return characters into a HTML block formatted with white-space: pre-wrap?

I've got an application which is receiving a SOAP message, and logging the message to a file. Our logging code has always stripped new-line characters so on Unix, this is a one-line log entry. The incoming message is windows format CRLF though, so after stripping the new-line, I'm left with lone carriage returns.

The log viewer screen on the application shows a table with the log entries having white-space: pre-wrap formatting. On my browser at least, this looks great, with lone carriage returns working just the same as a new-line or CRLF.

Is this reliable behaviour?


Solution

  • No, it's not reliable behavior.

    As such the previous answer was incorrect, and I hoped to add some context as to why.

    This was initially pointed out by @GSerg in a comment below as a reply to the original answer. So credits to him for noticing this.

    • CR = Carriage Return (\r, 0x0D in hexadecimal, or 13 in decimal) does not cause a line break with either white-space: pre-wrap or white-space: pre-line.

    • LF = Line Feed (\n, 0x0A in hexadecimal, or 10 in decimal) does cause a line-break with both white-space: pre-wrap or white-space: pre-line, also for combinations such as 
 where it's combined with a carriage return.

    He provided evidence for this in jsfiddle.net/n135a8wq.

    This also makes sense when you look at CR and LF origins from typewriters, where LF moved the paper up (but kept the horizontal position identical) and CR brought back the "carriage" so that the next character typed would be at the leftmost position on the paper (but on the same line). CR+LF did both.

    Previous (Wrong) Answer

    Yeah, it's valid. Using white-space: pre-wrap; is exactly the same as using <pre>, except that it will naturally wrap lines according to the boundaries of its parent.

    However, you should consider making sure your CSS is cross-browser compliant.

    #log {
        white-space: pre-wrap;       /* CSS3 */
        white-space: -moz-pre-wrap;  /* Mozilla, since 1999 */
        white-space: -pre-wrap;      /* Opera 4-6 */
        white-space: -o-pre-wrap;    /* Opera 7 */
        word-wrap: break-word;       /* Internet Explorer 5.5+ */
    }
    

    You can also use white-space: pre; if you want line to push the boundaries of its parent to keep everything in the output on a single line