Styling the First Letter of Text with the ::first-letter Pseudo-Element in CSS


::first-letter Pseudo-element

The ::first-letter pseudo-element in CSS allows you to style the first letter of a block-level element (such as a paragraph, heading, or div) in a more decorative or distinctive manner. This pseudo-element targets the initial letter within the element's content, allowing you to apply unique styling to it.

Source Code :

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>::first-letter Pseudo-element</title>
    <style>
      h2 {
        color: green;
      }
      h2::first-letter {
        color: darkblue;
      }
      p::first-letter {
        color: darkblue;
        font-weight: bold;
      }
    </style>
  </head>
  <body>
    <h1>::first-letter Pseudo-element</h1>

    <h2>Sample Heading</h2>
    <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Veritatis aliquid sint nihil eaque dolor dolorum libero, dolorem in repellendus temporibus vero recusandae explicabo tempore mollitia laborum eum assumenda possimus consequatur.</p>

    <h2>Sample Heading</h2>
    <p>Lorem ipsum dolor, Veritatis aliquid sint nihil eaque dolor dolorum libero, dolorem in repellendus temporibus vero recusandae explicabo tempore mollitia laborum eum assumenda possimus consequatur.</p>
  </body>
</html>

Live Preview

The CSS code you provided defines styles for the h2 and p elements, as well as their respective ::first-letter pseudo-elements.

The Code sets the text color of all h2 elements to green. Any h2 heading on your web page will have its text colored in green.

Here, you are using the ::first-letter pseudo-element to target the first letter of all h2 elements. You are changing the color of the first letter within h2 elements to dark blue. This will make the first letter of each h2 heading stand out in dark blue while the rest of the text in the h2 elements remains green.

The Code targeting the first letter of all p (paragraph) elements. You are changing both the color and font weight of the first letter. The color is set to dark blue, similar to what you did with the h2 elements, and you are also making the first letter bold.


CSS Tutorial


Properties Reference


Cascading Style Sheet


Flexbox Tutorial


CSS Grid Tutorial


Transitions Properties


CSS Properties with Examples


CSS Selectors


CSS Pseudo Elements


CSS Attribute Selectors


Input Pseudo Classes


CSS Examples


CSS Animation Projects