Pseudo-element CSS ::first-letter chọn chữ cái đầu tiên của nội dung một phần tử. Tuy nhiên, pseudo-element này không hoạt động nếu phần tử là inline-level.
Cú pháp
selector::first-letter {
/* declarations */
}
Các thuộc tính được phép dùng với ::first-letter
- Font:
font,font-size,font-weight,font-style,font-variant,font-family - Color:
color,background-color - Spacing:
margin,padding,border,text-decoration,vertical-align(nếu float) - Text:
text-transform,line-height,float,clear
Ví dụ 1: Drop cap (Chữ cái đầu to) cho bài viết
<!DOCTYPE html>
<html>
<head>
<style>
div {
background-color: #32485d;
border: 5px solid black;
color: #959799;
padding: 20px;
max-width: 600px;
margin: 20px auto;
font-family: Georgia, serif;
line-height: 1.6;
}
p::first-letter {
font-size: 4em;
color: #f9f9f9;
float: left;
margin-right: 8px;
margin-top: 4px;
padding: 2px;
line-height: 1;
font-weight: bold;
}
</style>
</head>
<body>
<div>
<h2>Eclipse IDE</h2>
<p>"Eclipse là môi trường phát triển tích hợp (IDE) cho Java và các ngôn ngữ lập trình khác như C, C++, PHP, và Ruby v.v. Môi trường phát triển do Eclipse cung cấp bao gồm Eclipse Java development tools (JDT) cho Java, Eclipse CDT cho C/C++, và Eclipse PDT cho PHP, trong số những cái khác."</p>
</div>
</body>
</html>
Ví dụ 2: Style cho nhiều đoạn văn
<!DOCTYPE html>
<html>
<head>
<style>
p::first-letter {
font-size: 2em;
background-color: black;
color: #dc3545;
padding: 4px 8px;
border-radius: 4px;
margin-right: 6px;
float: left;
line-height: 1;
}
p { overflow: hidden; /* clear float */ }
</style>
</head>
<body>
<div>
<h2>Machine Learning Tutorials</h2>
<p>TensorFlow</p>
<p>Machine Learning with Python</p>
<p>Time Series</p>
<p>PyTorch</p>
</div>
</body>
</html>
Lưu ý quan trọng
- Chỉ hoạt động trên block-level elements (div, p, article, v.v.)
- Không hoạt động trên
display: inline,inline-block(trừ khi float) - Ký tự đầu tiên có thể là dấu ngoặc, dấu nháy — pseudo-element vẫn chọn nó
- Kết hợp với
::first-linecho hiệu ứng magazine chuyên nghiệp
Kết hợp ::first-letter + ::first-line
article p::first-line {
font-variant: small-caps;
font-weight: 500;
}
article p::first-letter {
font-size: 3.5em;
float: left;
margin: 0.05em 0.1em 0 0;
color: #c00;
}