Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 318
swati16 Avatar asked Jul 29 '12 14:07

swati16


2 Answers

Normally you would do this with the :first-letter pseudo-element, but seeing as you have :before content, which inserts text before the actual content of your paragraph, then rather than the first letter of the actual content, :first-letter would match the first letter of the :before content instead.

That means that instead of this:

<p class="normal">
  <p:before>Former - </p:before>
  <p.normal:first-letter>F</p.normal:first-letter>irst character of this paragraph will
  be normal and will have font size 40px;
</p>

You actually get this:

<p class="normal">
  <p:before>
    <p.normal:first-letter>F</p.normal:first-letter>ormer - 
  </p:before>
  First character of this paragraph will
  be normal and will have font size 40px;
</p>

Due to how CSS generated content works, I don't think there's a solution in pure CSS to reach the first letter of the actual content once you have inserted content before it.

As an alternative, you could use a span in place of the :first-letter pseudo-element, to which you can then apply the blue color, but that means you have to insert extra elements:

  <p class="normal"><span>F</span>irst character of this paragraph will
  be normal and will have font size 40px;</p>
p.normal span {
    font-size:40px;
    color:blue;
}
like image 103
BoltClock Avatar answered Sep 28 '22 11:09

BoltClock


šŸ‘‹ Hello.

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

āœŒ Cheers, šŸ¤µ Sean Sr.

like image 21
Sean Sr Avatar answered Sep 28 '22 13:09

Sean Sr