text-wrap

Baseline 2024 *
新推出

自 ⁨2024 年 3 月⁩ 起,此功能可在最新的裝置和瀏覽器版本上執行。此功能可能不適用於較舊的裝置或瀏覽器。

* 此特性的某些部分可能存在不同級別的支援。

text-wrap CSS 簡寫屬性控制元素內文字的換行方式。不同的值提供:

  • 排版改進,例如斷裂標題之間更平衡的行長
  • 一種完全關閉文字換行的方法。

試一試

text-wrap: wrap;
text-wrap: nowrap;
text-wrap: balance;
text-wrap: pretty;
text-wrap: stable;
<section class="default-example" id="default-example">
  <div class="whole-content-wrapper">
    <p>Edit the text in the box:</p>
    <div class="transition-all" id="example-element">
      <p contenteditable="">
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptatem aut
        cum eum id quos est.
      </p>
    </div>
  </div>
</section>
.whole-content-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
}

#example-element {
  border: 1px solid #c5c5c5;
  width: 250px;
}

構成屬性

此屬性是以下 CSS 屬性的簡寫:

語法

css
/* Keyword values */
text-wrap: wrap;
text-wrap: nowrap;
text-wrap: balance;
text-wrap: pretty;
text-wrap: stable;

/* Global values */
text-wrap: inherit;
text-wrap: initial;
text-wrap: revert;
text-wrap: revert-layer;
text-wrap: unset;

text-wrap 屬性指定為從以下值列表中選擇的單個關鍵字。

wrap

文字在適當的字元處(例如,在像英語這種使用空格分隔符的語言中是空格)換行,以最大限度地減少溢位。這是預設值。

nowrap

文字不跨行換行。它會溢位其包含元素,而不是斷到新行。

balance

文字以最佳方式平衡每行字元數的方式換行,從而提高佈局質量和可讀性。由於計算字元並在多行中平衡它們計算成本高昂,因此此值僅支援跨越有限行數(Chromium 為六行或更少,Firefox 為十行或更少)的文字塊。

pretty

結果與 wrap 相同,不同之處在於使用者代理將使用較慢的演算法,該演算法傾向於更好的佈局而不是速度。這適用於正文文字,其中良好的排版優於效能(例如,當應將孤行數保持在最低限度時)。

stable

結果與 wrap 相同,不同之處在於當用戶編輯內容時,他們正在編輯的行之前的行保持靜態,而不是整個文字塊重新換行。

描述

文字可以在內容塊(例如段落 (<p>) 或標題 (<h1>–<h6>))內跨行流動的方式有兩種。它們是使用者控制的強制換行和瀏覽器控制的軟換行text-wrap 屬性可用於提示瀏覽器如何控制軟換行

您為 text-wrap 選擇的值取決於您預計要設定樣式的文字行數、文字是否可 contenteditable,以及您是否需要優先考慮外觀或效能。

當樣式化內容僅限於少量行時,例如標題、說明和引用塊,可以新增 text-wrap: balance 以平衡每行字元數,從而提高佈局質量和可讀性。由於瀏覽器限制了受此屬性影響的行數,因此此值對效能的影響可以忽略不計。

對於較長的文字段落,可以使用 text-wrap: pretty。請注意,pretty 對效能有負面影響,因此應僅在佈局比速度更重要時用於較長的文字塊。

當用於contenteditable 內容時,stable 值可改善使用者體驗。此值確保當用戶編輯文字時,正在編輯區域中的前幾行保持穩定。

正式定義

初始值wrap
應用於文字和塊容器
繼承性
百分比作為簡寫中的每個屬性
計算值作為簡寫中的每個屬性
動畫型別作為簡寫中的每個屬性

正式語法

text-wrap = 
<'text-wrap-mode'> ||
<'text-wrap-style'>

<text-wrap-mode> =
wrap |
nowrap

<text-wrap-style> =
auto |
balance |
stable |
pretty |
avoid-orphans

示例

基本文字換行值比較

HTML

html
<h2 class="wrap" contenteditable="true">
  The default behavior; the text in the heading wraps "normally"
</h2>

<h2 class="nowrap" contenteditable="true">
  In this case the text in the heading doesn't wrap, and overflows the container
</h2>

<h2 class="balance" contenteditable="true">
  In this case the text in the heading is nicely balanced across lines
</h2>

CSS

css
.wrap {
  text-wrap: wrap;
}

.nowrap {
  text-wrap: nowrap;
}

.balance {
  text-wrap: balance;
}

h2 {
  font-size: 2rem;
  font-family: sans-serif;
}

結果

示例中的文字是可編輯的。更改文字,新增長單詞,以檢視不同行和單詞長度如何影響換行。

規範

規範
CSS 文字模組第 4 級
# text-wrap-shorthand

瀏覽器相容性

另見