CSS - 伪元素 - ::first-letter



::first-letter 伪元素用于对块级元素第一行首字母应用特殊效果或样式。只有当元素前面没有其他内容(如图片或内联表格)时,此功能才适用。

伪元素 ::first-letter 应用于文本的首字母,在以下情况下:

  • 位于首字母之前或之后标点符号会被考虑在匹配范围内。

  • 某些语言具有连写在一起的大写双字母组合,在这种情况下,::first-letter 伪元素会将双字母组合的两个字母一起匹配。

  • ::before 伪元素和content 属性组合起来在元素开头添加一些文本时,::first-letter 伪元素将匹配新生成内容的首字母。

一些 CSS 属性可与 ::first-letter 伪元素一起使用,如下所示:

语法

selector::first-letter { /* ... */ }

CSS ::first-letter 示例

以下示例演示了 ::first-letter 伪元素的简单用法。

Open Compiler
<html> <head> <style> #flavor { display: block; font-size: 18px; color: black; width: 500px; } li { padding: 5px 5px; font-size: 16px; color: black; background-color: #fff; margin-top: 25px; width: 300px; transition: all 0.3s ease; } li::first-letter { font-size: 2em; color: crimson; } </style> </head> <body> <form> <ul id="flavor"> Ice cream Flavors: <li> Cookie dough</li> <li> Pistachio</li> <li> Cookies & Cream</li> <li> Cotton Candy</li> <li> Lemon & Raspberry Sorbet</li> </ul> </form> </body> </html>

以下是在文本开头使用特殊字符的另一个示例。

Open Compiler
<html> <head> <style> p::first-letter { color: blue; font-size: 2.5em; } </style> </head> <body> <p>-Hyphen</p> <p>_Underscore</p> <p>"Quotation marks</p> <p>#Hash</p> </body> </html>
广告