skip to Main Content

I am having a problem applying CSS rules to an element inside span tag when using a pseudo-element selector.

I have this HTML code

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>A Simple Page</title>
<link rel="stylesheet" href="styles.css" />
</head>
<body>
  <div class="content">
      <p><span class="firstletter">H</span>ello World.</p>
  </div>
</body>
</html>

Now I am trying to apply styles on the H letter of Hello

when I am doing this without using pseudo-element selector, like this

.firstletter {
    color: red;
    font-weight: bold;
    font-size: 200%;
}

It works fine; the CSS rules are getting applied to the letter H.

But since I am learning the pseudo-element selector and trying to apply it on the letter H, the rules are not getting applied at all

.content:first-letter {
    color: red;
    font-weight: bold;
    font-size: 200%;
}

But I think it should work. What is the issue here?

2

Answers


  1. The selector needs to be .content p:first-letter

    .content p:first-letter {
      color: red;
      font-weight: bold;
      font-size: 200%;
    }
    <!DOCTYPE html>
    <html lang="en">
    
    <head>
      <meta charset="utf-8" />
      <title>A Simple Page</title>
      <link rel="stylesheet" href="styles.css" />
    </head>
    
    <body>
      <div class="content">
        <p>Hello World.</p>
      </div>
    </body>
    
    </html>

    Or if you need it to be more precise in the actual situation, use for example .content > p:first-of-type:first-letter

    Login or Signup to reply.
  2. You can also do it using the selector : first-child

    .content span:first-child {
        color: red;
        font-weight: bold;
        font-size: 200%;
    }
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="utf-8" />
    <title>A Simple Page</title>
    <link rel="stylesheet" href="styles.css" />
    </head>
    <body>
      <div class="content">
          <p><span class="firstletter">H</span>ello World.</p>
      </div>
    </body>
    </html>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search