萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> Div CSS 教學

CSS文本縮進實現段落首行縮進兩字符:text-indent屬性與em單位深度解析

核心屬性:text-indent

p {
  text-indent: 2em;  /* 首行縮進 2 個字符寬度 */
}

為什麼用 em 單位?

  • 相對單位:1em = 當前元素的 font-size 計算值
  • 自適應字號:字體大小變化時,縮進距離自動按比例縮放
  • 中文排版習慣:標準段落首行縮進 2 個漢字寬度,2em 精確對應

實戰示例

.article-content {
  font-size: 16px;
  line-height: 1.8;
  text-indent: 2em;           /* 32px 縮進 */
  margin-block: 1.5em;        /* 段落間距 1.5em = 24px */
}

/* 響應式字號下自動縮放 */
@media (max-width: 768px) {
  .article-content { font-size: 15px; }  /* 縮進自動變為 30px */
}

避坑指南:常見錯誤與修正

錯誤寫法問題正確寫法
text-indent: 24px固定像素,字號變化時縮進不變,破壞視覺比例text-indent: 2em
text-indent: 2rem相對根元素字號,非當前段落字號text-indent: 2em
用空格/  強行縮進語義錯誤、無法響應、屏幕閱讀器讀出空格text-indent: 2em
p { text-indent: 2em; } 作用於 <div>只對塊級容器首行生效,內部<p>不生效直接作用於 p、li、dd 等塊級文本容器

進階場景處理

1. 首段不縮進(刊首段落)

.article-content p:first-child { text-indent: 0; }
/* 或 */
.article-content p + p { text-indent: 2em; }  /* 相鄰兄弟選擇器:從第二段開始縮進 */

2. 標題後的段落不縮進

.article-content h2 + p,
.article-content h3 + p,
.article-content h4 + p { text-indent: 0; }

3. 列表項、引用塊不縮進

.article-content li,
.article-content blockquote,
.article-content pre,
.article-content table { text-indent: 0; }

4. 垂直書寫模式下的縮進

.vertical-text {
  writing-mode: vertical-rl;   /* 垂直排版:右到左,上到下 */
  text-indent: 2em;            /* 在垂直方向上產生「首行縮進」效果 */
}

5. 配合 ::first-letter 做首字下沉

.drop-cap::first-letter {
  float: left;
  font-size: 3.5em;
  line-height: 1;
  margin: 0.05em 0.1em 0 0;
  font-weight: 700;
  color: var(--color-primary);
}
.drop-cap { text-indent: 0; }  /* 首字下沉段落不再需要縮進 */

工程化建議

  1. 設計系統 Token 化:--text-indent: 2em,統一管理,主題切換時同步調整
  2. 重置樣式表包含:
    p, li, dd, blockquote { text-indent: 0; }  /* 重置默認 */
    .article p { text-indent: var(--text-indent); } /* 文章區域啟用 */
    
  3. Markdown 渲染輸出:確保輸出標準<p>標籤,而非<br>換行,才能正確應用text-indent
  4. 無障礙:text-indent 不影響屏幕閱讀器朗讀,優於空格方案

總結:text-indent: 2em 是中文段落首行縮進的標準、語義化、響應式、無障礙的最佳方案。拒絕空格硬編碼,擁抱相對單位與現代排版規範。

copyright © 萬盛學電腦網 all rights reserved