text-indent 指定文本塊中第一行文本前的縮進量。中文排版習慣首行縮進 2 個字符(2em)。
.article-content p {
text-indent: 2em; /* 相對當前字體大小的 2 倍 */
text-align: justify; /* 兩端對齊 */
text-justify: inter-ideograph; /* IE/Edge 中文兩端對齊優化 */
}
<style>
.article {
max-width: 800px;
margin: 0 auto;
padding: 20px;
font-family: 'Microsoft JhengHei', 'PingFang TC', sans-serif;
line-height: 1.8;
color: #333;
}
.article p {
text-indent: 2em; /* 首行縮進 2 字符 */
text-align: justify; /* 兩端對齊 */
text-justify: inter-ideograph; /* IE/Edge 中文優化 */
margin: 0 0 1.5em; /* 段落間距 */
}
/* 現代瀏覽器標準屬性 */
.article p {
text-align-last: justify; /* 最後一行也兩端對齊 */
}
/* 針對 Chrome/Safari 的最後一行對齊 */
@media screen and (-webkit-min-device-pixel-ratio: 0) {
.article p::after {
content: "";
display: inline-block;
width: 100%;
overflow: hidden;
height: 0;
}
}
</style>
<div class="article">
<p>第一段文字內容...</p>
<p>第二段文字內容...</p>
<p class="no-indent">這段不需要首行縮進(如標題、引言、代碼塊前說明)</p>
<p>第三段繼續縮進...</p>
</div>
<!-- 方法一:類名覆蓋 -->
<p class="no-indent">不縮進的段落</p>
<!-- 方法二:內聯樣式 -->
<p style="text-indent: 0;">不縮進的段落</p>
<style>
.no-indent { text-indent: 0; }
</style>
.article h1, .article h2, .article h3,
.article ul, .article ol, .article blockquote,
.article pre, .article table {
text-indent: 0;
}
.article p:first-child {
text-indent: 0;
}
/* 或:第一章第一段不縮進 */
.article > p:first-of-type {
text-indent: 0;
}
.chinese-justify {
text-align: justify;
text-justify: inter-ideograph; /* IE/Edge */
text-align-last: justify; /* 現代標準:最後一行也對齊 */
-moz-text-align-last: justify; /* Firefox */
-webkit-text-align-last: justify; /* Chrome/Safari */
/* Chrome/Safari 修正:強制最後一行展開 */
/* 需配合 ::after 偽元素 */
}
@media screen and (-webkit-min-device-pixel-ratio: 0) {
.chinese-justify::after {
content: "";
display: inline-block;
width: 100%;
height: 0;
overflow: hidden;
}
}
| 值 | 說明 | 範例 |
|---|---|---|
2em | 相對字體大小,推薦中文首行縮進 | 標準段落 |
24px | 固定像素,不隨字體縮放 | 精確設計稿還原 |
5% | 相對父容器寬度 | 響應式縮進 |
-2em | 負值:首行向左突出(掛鉤縮進) | 清單項、引用符號 |
each-line | CSS Text 3:每行(含強制換行)縮進 | 詩歌、歌詞 |
hanging | CSS Text 3:首行不縮進,其餘行縮進 | 參考文獻、字典 |
[dir="rtl"] .article p {
text-indent: 2em; /* 同樣生效,方向自動反轉 */
}
/***** 文章正文標準樣式 *****/
.article-content {
line-height: 1.8;
font-size: 1rem;
}
.article-content p {
margin: 0 0 1.5em;
text-indent: 2em;
text-align: justify;
text-justify: inter-ideograph;
text-align-last: justify;
}
.article-content p:first-child,
.article-content h1, .article-content h2, .article-content h3,
.article-content blockquote, .article-content pre,
.article-content ul, .article-content ol {
text-indent: 0;
}
/***** Chrome/Safari 最後一行對齊修正 *****/
@media screen and (-webkit-min-device-pixel-ratio: 0) {
.article-content p::after {
content: "";
display: inline-block;
width: 100%;
height: 0;
overflow: hidden;
}
}