pre 預設會保留所有空白與換行,也因此當內容是一長串沒有空格的字串時,就會撐破容器。要讓它乖乖換行,關鍵是 white-space 與 word-wrap 這兩個屬性。
/* pre 強制換行 */
pre {
white-space: pre-wrap !important; /* 保留空白並允許換行 */
word-wrap: break-word !important; /* 連續字元處斷行 */
/* white-space: normal !important; */ /* 忽略空白並換行 */
}
white-space: pre-wrap 保留原始縮排與空行,同時允許自動換行,適合顯示程式碼;word-wrap: break-word 則負責處理那些完全沒有斷點的長字串。兩者一起用,覆蓋面最完整。若你不在乎保留原始空白,改用 white-space: normal 也能達到換行效果。
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>CSS 實現 pre 強制換行</title>
<style>
pre {
border: #CCC solid 1px;
padding: 10px;
background-color: #F9F9F9;
font-family: "Courier New", Courier, Arial;
font-size: 12px;
line-height: 1.75;
white-space: pre-wrap !important;
word-wrap: break-word !important;
}
</style>
</head>
<body>
<div style="width:450px;">
<pre>
1111111111111111111111111111111111111111111111111111111111
何問起為您提供 jQuery 特效、彈出層、導覽選單、下拉選單與焦點圖等前端資源。
</pre>
</div>
</body>
</html>