skip to Main Content

I want to style the first letter of the <p> element which is parent of a <section> element which has a <p> element. I will provide an idea of what I was able to come up with.

HTML:

This HTML is not a rigid structure. It may change, by which I mean there are various possibilities for where the first paragraph can occur. My client may have a first section with a paragraph or he may have a paragraph in the second section. That’s why I’m trying to use :has()

eg: 1

<body>
  <section>
    <img src="" alt="" />
  </section>

  <section>
    <p>//something 1</p>
    <img src="" alt="" />
    <p>//something 2</p>
    <p>//something 3</p>
  </section>

  <section>
    <img src="" alt="" />
  </section>

  <section>
    <p>//something 4</p>
    <p>//something 5</p>
  </section>
</body>

or

eg: 2

<body>
  <section>
    <p>//something 1</p>
    <img src="" alt="" />
    <p>//something 2</p>
    <p>//something 3</p>
  </section>

  <section>
    <img src="" alt="" />
  </section>

  <section>
    <p>//something 4</p>
    <p>//something 5</p>
  </section>
</body>

CSS:

section:has(p):first-child p::first-letter{
 background:red;
}

I also tried

p:first-child::first-letter{
 background:red;
}

Here in my examples I only want to target <p>//something 1</p> but I keep selecting both <p>//something 1</p> and <p>//something 4</p>. I think it’s happening because everything is in different HTML depth but idk what to do anymore. So help me CSS gods.

Here is a codepen link I have created to demonstrate and playaround: codepen link

2

Answers


  1. The :nth-of-type pseudo class should do it:

    section:nth-of-type(2) > p:nth-of-type(1) {
      background: red;
    }
    <section>
      <img src="" alt="" />
    </section>
    
    <section>
      <p>//something 1</p>
      <img src="" alt="" />
      <p>//something 2</p>
      <p>//something 3</p>
    </section>
    
    <section>
      <img src="" alt="" />
    </section>
    
    <section>
      <p>//something 4</p>
      <p>//something 5</p>
    </section>
    Login or Signup to reply.
  2. Perhaps in your case it is necessary to search for all section:has(p:first-of-type) ~ section p:first-letter and reset :first-letter background-color in <p>:

    section p:first-of-type:first-letter {
      background-color: red;
    }
    section:has(p:first-of-type) ~ section p:first-letter {
      background-color: unset;
    }
    <section>
      <p>//something 1</p>
      <img src="" alt="" />
      <p>//something 2</p>
      <p>//something 3</p>
    </section>
    
    <section>
       <img src="" alt="" />
    </section>
    
    <section>
      <p>//something 4</p>
      <p>//something 5</p>
    </section>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search