CSS 文字樣式 (Text)

CSS 提供多個屬性來控制文字的顯示方式,包括顏色、行高、間距、對齊等。

color(文字顏色)

color 設定文字的顏色。

p {
  color: #333333;
}

a {
  color: blue;
}

.error {
  color: rgb(255, 0, 0);
}

line-height(行高)

line-height 設定行與行之間的高度。

p {
  line-height: 1.5;      /* 字體大小的 1.5 倍(推薦) */
}

.tight {
  line-height: 1.2;
}

.loose {
  line-height: 2;
}

/* 也可以用固定單位 */
.fixed {
  line-height: 24px;
}

建議使用無單位數值,這樣子元素會繼承倍數而不是固定值。

letter-spacing(字元間距)

letter-spacing 設定字元與字元之間的間距。

.wide {
  letter-spacing: 2px;
}

.tight {
  letter-spacing: -1px;
}

/* 標題常用較大的字元間距 */
h1 {
  letter-spacing: 0.1em;
}

word-spacing(單字間距)

word-spacing 設定單字與單字之間的間距(對中文效果不明顯)。

p {
  word-spacing: 5px;
}

text-align(文字對齊)

text-align 設定文字的水平對齊方式。

.left {
  text-align: left;      /* 靠左對齊(預設) */
}

.center {
  text-align: center;    /* 置中對齊 */
}

.right {
  text-align: right;     /* 靠右對齊 */
}

.justify {
  text-align: justify;   /* 左右對齊(兩端對齊) */
}

text-indent(首行縮排)

text-indent 設定段落第一行的縮排距離。

p {
  text-indent: 2em;      /* 縮排兩個字 */
}

負值可以製作凸排效果:

.hanging {
  text-indent: -2em;
  padding-left: 2em;
}

vertical-align(垂直對齊)

vertical-align 設定行內元素或表格儲存格內容的垂直對齊方式。

img {
  vertical-align: middle;
}

/* 常用於對齊圖示和文字 */
.icon {
  vertical-align: -2px;
}

常用值:

  • baseline:基線對齊(預設)
  • top:頂部對齊
  • middle:中間對齊
  • bottom:底部對齊
  • text-top:與文字頂部對齊
  • text-bottom:與文字底部對齊
vertical-align 只對行內元素和表格儲存格有效,對區塊元素無效。要垂直置中區塊元素,請使用 Flexbox 或其他方式。

white-space(空白處理)

white-space 設定如何處理元素內的空白字元和換行。

.nowrap {
  white-space: nowrap;    /* 不換行 */
}

.pre {
  white-space: pre;       /* 保留空白和換行(像 <pre> 標籤) */
}

.pre-wrap {
  white-space: pre-wrap;  /* 保留空白,但會自動換行 */
}

.pre-line {
  white-space: pre-line;  /* 合併空白,保留換行 */
}
連續空白換行符號自動換行
normal合併忽略
nowrap合併忽略
pre保留保留
pre-wrap保留保留
pre-line合併保留

direction(文字方向)

direction 設定文字的書寫方向。

.rtl {
  direction: rtl;    /* 從右到左(阿拉伯文、希伯來文) */
}

.ltr {
  direction: ltr;    /* 從左到右(預設) */
}

實用範例

段落樣式

p {
  color: #333;
  line-height: 1.8;
  text-indent: 2em;
  text-align: justify;
}

標題樣式

h1 {
  color: #222;
  letter-spacing: 0.05em;
  text-align: center;
}

強制不換行

.single-line {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;  /* 超出部分顯示 ... */
}