Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> CSS

CSS text-indent: Thụt lề dòng đầu tiên

Thuộc tính CSS text-indent giúp chúng ta thiết lập độ thụt lề của dòng đầu tiên của một phần tử.

Cú pháp

selector {
    text-indent: /* length | percentage */;
}

Giá trị: độ dài (px, em, rem) hoặc phần trăm (so với chiều rộng khối chứa). Giá trị âm được phép (thụt lùi - hanging indent).

Ví dụ 1: Thụt lề 25% cho bài viết

<!DOCTYPE html>
<html>
<head>
<style>
div { display: flex; float: left; margin: auto; padding: 10px; }
article {
    text-indent: 25%;
    background-color: darkseagreen;
    padding: 15px; font-size: 1.3em;
}
h3 { text-indent: -0.8em; } /* Hanging indent */
</style>
</head>
<body>
<div>
    <h3>Doing it our way. Nothing gonna turn us back now.</h3>
    <article>
        This is demo paragraph. This is demo paragraph. This is demo paragraph.
        This is demo paragraph. This is demo paragraph. This is demo paragraph.
        This is demo paragraph. This is demo paragraph. This is demo paragraph.
        This is demo paragraph. This is demo paragraph. This is demo paragraph.
    </article>
</div>
</body>
</html>

Ví dụ 2: Thụt lề cho list items

<!DOCTYPE html>
<html>
<head>
<style>
ul {
    list-style: none;
    display: flex; float: left;
    text-indent: 23px;
    background-image: url("angular-4.jpg");
    font-size: 1.5em;
}
li { border: thin solid; }
</style>
</head>
<body>
<ul>
    <li>This is demo text. This is demo text.</li>
    <li>Angular 4 là framework JavaScript cho web apps...</li>
    <li>Angular cung cấp built-in features cho animation, http, materials...</li>
    <li>This is demo text. This is demo text.</li>
</ul>
</body>
</html>

Hanging Indent (Thụt lùi) - Kỹ thuật phổ biến

.reference-entry {
    text-indent: -1.5em;
    padding-left: 1.5em;
}
/* Dòng 1 bắt đầu ở lề trái, các dòng sau thụt vào 1.5em */

Lưu ý quan trọng

  • Chỉ ảnh hưởng đến dòng đầu tiên của block container
  • Phần trăm (%) tính theo width của containing block, không phải font-size
  • Không tác động trên các phần tử display: inline
  • Kết hợp với ::first-letter để tạo drop cap + thụt lề

Ứng dụng thực tế

/ * Văn bản in ấn, sách, báo cáo */
p + p { text-indent: 1.5em; } /* Chỉ thụt từ đoạn 2 trở đi */

/ * Danh sách tài liệu tham khảo */
.bibliography li { text-indent: -2em; padding-left: 2em; }

/ * Code block (tránh thụt lề) */
pre, code { text-indent: 0; }

/ * RTL languages */
[dir="rtl"] p { text-indent: 1.5em; } /* Tương tự, nhưng bên phải */