CSS - 偽元素 - ::first-letter



::first-letter 偽元素用於對塊級元素第一行首字母應用特殊效果或樣式。只有當元素前面沒有其他內容(如圖片或內聯表格)時,此功能才適用。

偽元素 ::first-letter 應用於文字的首字母,在以下情況下:

  • 位於首字母之前或之後標點符號會被考慮在匹配範圍內。

  • 某些語言具有連寫在一起的大寫雙字母組合,在這種情況下,::first-letter 偽元素會將雙字母組合的兩個字母一起匹配。

  • ::before 偽元素和content 屬性組合起來在元素開頭新增一些文字時,::first-letter 偽元素將匹配新生成內容的首字母。

一些 CSS 屬性可與 ::first-letter 偽元素一起使用,如下所示:

語法

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

CSS ::first-letter 示例

以下示例演示了 ::first-letter 偽元素的簡單用法。

<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> 

以下是在文字開頭使用特殊字元的另一個示例。

<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>
廣告