Article directory
foreword
HTML
If the newline and carriage return symbols ( \n
and ) don't seem to be working in your \r
, there are several possible causes:
html does not interpret whitespace characters
In
HTML
, consecutive whitespace characters (including newline and carriage return characters) are usually interpreted as a single space. This isHTML
the default behavior and is intended to ensure page display consistency and readability. If you want to actually display line breaks on the page, you need to useHTML
a tag<br>
orCSS
an attributewhite-space: pre-line;
.<!-- 使用 <br> 标签进行换行 --> <p>This is the first line.<br>This is the second line.</p> <!-- 或者使用 CSS 属性 white-space: pre-line; --> <style> .pre-line { white-space: pre-line; } </style> <p class="pre-line">This is the first line. This is the second line.</p>
Effect of CSS styles
You may have applied certain
CSS
styles that cause line breaks and carriage returns not to work. Check yourCSS
file to see if there are settingswhite-space
ordisplay
other properties that might be affecting how the text is displayed.
specific text area
Some elements, such as
<pre>
<element>, preserve whitespace characters in the text without automatically merging them into a single space. You can try line feed and carriage return tests in these elements.
white-space
MDN
white-space
Attribute used to set how to handle whitespace characters (en-US) within the element .
This property specifies two things:
whether whitespace is merged , and how.
Whether to wrap lines, and how to wrap lines.
To allow words to be truncated within themselves, use overflow-wrap , word-break , or hyphens instead.
w3school
value | describe |
---|---|
normal |
default. Whitespace is ignored by the browser. |
pre |
White space is preserved by the browser. It behaves like a tag HTML in <pre> . |
nowrap |
The text will not wrap, the text will continue on the same line until <br> a tag is encountered. |
pre-wrap |
Whitespace sequences are preserved, but line breaks are performed normally. |
pre-line |
Merge whitespace sequences, but preserve newlines. |
inherit |
Specifies that the attribute's value should be inherited from the parent element white-space . |