如何渲染 HTML 字串並保留空格和換行符?
有時在編寫 HTML 檔案內容時,可能需要保留空格和換行符。您可能已經注意到,當您嘗試在段落<p>標籤或<div>標籤中寫入很多空格或換行符時,在網頁瀏覽器中渲染 HTML 頁面時,這些空格或換行符是不可見的。本文將介紹如何在渲染 HTML 頁面時保留這些空格。
渲染 HTML 字串並保留空格和換行符
使用 Pre 標籤
保留空格和換行符的一種方法是使用預格式化的 HTML 標籤<pre>。它以固定寬度字型顯示文字,並按在<pre>標籤中寫入的 HTML 程式碼顯示文字。
示例
<!DOCTYPE html> <html> <body> <h3>HTML String Preserving Spaces and Line Breaks</h3> <pre> Hello world! Welcome to Tutorialspoint. Today we are learning about preserving spaces and line breaks in HTML. </pre> </body> </html>
輸出
使用 white-space 屬性
另一種方法是使用樣式。這可以與任何 HTML 元素一起使用,例如段落<p>標籤、<div>標籤和<span>標籤。我們只需要指定 style 屬性並將white-space定義為 pre-wrap。
示例
<!DOCTYPE html> <html> <body> <h3>HTML String Preserving Spaces and Line Breaks</h3> <div style="white-space:pre-wrap;"> Hello World! Welcome to Tutorialspoint. Today we are learning about preserving spaces and line breaks in HTML. </div> </body> </html>
輸出
廣告