Search code examples
csspseudo-element

How to apply CSS to the first letter after :before content?


<!DOCTYPE html>
<html lang="en">
<head>
<style type="text/css">
p:before {  
    content:"Former - "; 
    color:red;
    font-family:"Tahoma" ,Times New Roman;
    font-size:70%;
}

p.normal:first-letter {
    font-size:40px;
    color:blue;
}
</style>
</head>
<body>
  <p class="normal">First character of this paragraph will
  be normal and will have font size 40px;</p>
</body>
</html>

Here, the content in the :before pseudo-element is displaying in red, but I also want to style the character "F" of "First character of this paragraph" in blue. But instead, I see the "F" of "Former - " in blue.

What I want is to apply both :before and first letter of .normal after the :before content to the same paragraph. Is this possible? If so, how?


Solution

  • In case you can not edit the HTML without JavaScript for example, you can use pure CSS so long as you are styling the :before or :after content of a "block-level" element.

    p:before {
      content: 'Wisdom'
    }
    
    p:first-letter {
      font-size: 7vw;
    }
    <p></p>

    Please note: The ::first-letter CSS pseudo-element applies styles to the first letter of the first line of a block-level element, but only when not preceded by other content (such as images or inline tables).

    Attribution: https://developer.mozilla.org/en-US/docs/Web/CSS/::first-letter