Filip
Filip

Reputation: 1864

How to target first letter of p only if it's first child of parent?

for my site with user-generated content, I would like to add drop caps but only if the p element is first child of article (for example).

I tried various combinations of first-child along with :is but couldn't get this to work.

For example with this markup:

<article>
    <h2>Heading</h2>
    <p>Text..</p>
</article>

I don't want the drop cap to appear, because there is the heading already.

But with this:

<article>
    <p>Text.. (this should start with drop cap)</p>
    <p>Text..</p>
</article>

I want to have drop cap for the first letter.

Is this possible to do via CSS only?

There's also a case where the first p contains just img due to Markdown parser, but I guess there is not much I can do about that.

Upvotes: 0

Views: 94

Answers (1)

Fabian S.
Fabian S.

Reputation: 2529

Use article p:first-child:first-letter to target the first letter of the first p-child of every article.

article p:first-child:first-letter {
  font-size: 20px;
}
<article>
  <p>Text.. (article without heading and dropcap)</p>
  <p>Text..</p>
</article>
<hr/>
<article>
  <h1>Article with heading and without dropcap</h1>
  <p>Text..</p>
  <p>Text..</p>
</article>

See https://developer.mozilla.org/en-US/docs/Web/CSS/:first-child and https://developer.mozilla.org/en-US/docs/Web/CSS/::first-letter for how those two pseudo-classes work.

Upvotes: 3

Related Questions