如何在HTML中停用文字換行?
自動換行是指自動將一行結尾的單詞移到新的一行,以保持文字在頁邊距內。在HTML中,這意味著元素內的文字會根據該元素的邊界自動換行。
示例
讓我們考慮一個示例,其中我們有一個<div>元素包含一些文字,並且它的樣式設定為固定寬度。
<!DOCTYPE html> <html> <head> <style> div{ margin:20px; background-color:lightblue; width:90px; } </style> </head> <body> <div> Hi there, Have a good day! </div> </body> </html>
我們可以看到,文字根據容器的邊界換行,在本例中是<div>元素的寬度。
CSS white-space 屬性
CSS `white-space` 屬性控制如何處理元素內的空白字元。空白字元通常是空格序列或換行符。此屬性可以應用於任何元素的內聯內容。多餘的空格將合併為一個空格,換行符將被刪除,並且行將被換行以適應其容器。
語法
white-space: normal|nowrap|pre|pre-line|pre-wrap
其中:
normal: 空格序列將合併成單個空格。必要時,文字將換行。這是標準設定。
nowrap: 空格序列將合併成單個空格。文字將永遠不會換行到下一行。文字將繼續在同一行上,直到遇到`
`標籤。pre: 瀏覽器保留空白字元。只有換行符才會導致文字換行。
pre-line: 空格序列將合併成單個空格。必要時,文字將在換行符處換行。
pre-wrap: 瀏覽器保留空白字元。文字將在需要時換行,以及在換行符處換行。
在本教程中,我們將討論如何使用CSS `white-space` 屬性來防止HTML中的文字換行。
使用 `white-space: nowrap` 屬性
當CSS `white-space` 屬性設定為`nowrap`時,任何兩個或多個空格的序列都將顯示為單個空格。除非顯式指定,否則元素的內容將不會換行。
示例
下面的示例演示瞭如何使用`whitespace`屬性的`nowrap`值停用文字換行。
<!DOCTYPE html> <html> <head> <title>How to Disable Word Wrapping in HTML?</title> <style> .container{ width:300px; height:30px; background-color:linen; white-space: nowrap; } p{ font-size:12px; } </style> </head> <body> <h3>An inspiring quote</h3> <div class="container"> Winning is not necessarily finishing first but finishing well, to the best of your God-given abilities. When you embrace this concept in your life, you will be relieved from the stress of competing to finish first, to win in life. </div> <p>Note: Word wrapping is disabled here</p> </body> </html>
使用 `white-space: pre`
在前面的示例中,有一些換行符允許文字獨立存在(在程式碼中)。當文字在瀏覽器中呈現時,換行符似乎被刪除了。第一個字母之前的額外空格也被刪除了。我們可以使用`white-space: pre`強制瀏覽器顯示這些換行符和額外的空格字元。
它被稱為`pre`,因為其行為與文字包含在<pre></pre>標籤中相同(預設情況下,這些標籤以這種方式處理空白字元和換行符)。空白字元的處理方式與HTML中相同,並且文字不會換行,除非程式碼中存在換行符。這在顯示程式碼時特別有用,因為程式碼的美觀需要一些格式。
示例
下面的示例演示瞭如何使用`whitespace`屬性的`pre`值停用文字換行。
<!DOCTYPE html> <html> <head> <title>How to Disable Word Wrapping in HTML?</title> <style> .container{ width:400px; height:30px; background-color:aliceblue; border:1px solid azure; white-space: pre; } p{ margin-top:20px; font-size:13px; } </style> </head> <body> <h3>Talk more, Type less</h3> <div class="container"> People often undervalue the positive impact on their relationships by speaking versus text alone. So, if you’ve been putting off having a difficult conversation or you’re just more comfortable sending a written message, take a moment to consider whether it might be more fruitful to rise above your discomfort and brave a real conversation instead. </div> <p>Note: Word wrapping is disabled here</p> </body> </html>