Css first element after another (with other ones between)

Id like to capitalize the first letter of the first p element after a title (such as h3), even between h3 and p there are other elements, such as an img.
This code indeed works

h3 + p:first-letter {[some code]}

but, if I have an image between h3 and p, it doesn’t work any more.

It would be possible?

Assuming you only expect one element to be in the way you could just do this:

h3 + p:first-letter,
h3 + :not(p) + p:first-letter {
  font-size: 2rem;
  color: red;

If you may have 2 or 3 elements in the way then you could extend the above.

1 Like

Thank you very, very much!

To be honest that’s really crazy. Does anybody use this in the real world?

In JavaScript it is

Array.from(document.querySelectorAll('h3 p')).forEach((element) =>
      element.textContent = element.textContent.charAt(0).toUpperCase() + element.textContent.slice(1);

We’ve been using stuff like that for 10 years :slight_smile:

It’s very useful in certain cases.

1 Like

I try to imagine what happens if someone wants to update the site content and all his first letters in a paragraph are automatically converted to upper case even if he doesn’t want to.

At the end I find it very ugly to change static text content with code (doesn’t matter if With CSS or JavaScript).

We are not changing any content at all but just styling it. That’s what css is for and we do it all the time. :wink:

If the style guide for your site is for the first letter of the first paragraph only after a level 3 heading to be coloured then that seems exactly what css was made for.

Of course you can limit scope as required but all css is just like that in some way so I don’t really get your point.

You do have to take care when applying rules globally but it does sometimes save adding classes all over the place when not needed.

Btw I don’t think your script is correct as an h3 cannot have a p as a descendant and we are only targeting the first p element that occurs after the h3 as there may be an image after the h3.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.