0

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.

Filip
  • 1,824
  • 4
  • 18
  • 37
  • Does this answer your question? [How to change the CSS style of first-letter when hover over a parent element?](https://stackoverflow.com/questions/55612/css-to-select-style-first-word) along with a multitude of similar answers found by searching SO. – Rob Oct 20 '21 at 10:18

1 Answers1

3

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.

Fabian S.
  • 2,441
  • 2
  • 24
  • 34
  • 1
    Big facepalm for me.. looks like I misunderstood how `:first-child` really works – Filip Oct 20 '21 at 07:15
  • 1
    It's often mixed up with how `:first-of-type` (https://developer.mozilla.org/en-US/docs/Web/CSS/:first-of-type) works, so no worries, it's a common mistake. Most cases i use one of those i have to look it up myself because those cases are very rare for me. – Fabian S. Oct 20 '21 at 07:16