0

I wanted to know if it's possible to style <span> tags differently based on where it appears inside a <p> tag.

Ex:

<p><span>Lorem</span> ipsum dolor sit amet</p>
<p>Inquit, <span>contingit</span> omnibus fidibus, ut incontentae sint.</p>
<p>Unum est sine dolore esse, alterum <span>cum voluptate.</span></p>
  • If the span appears before any other text, I want to style it red,
  • If the span has text before and after it, I want to style it blue,
  • If the span has no text appear after it, I want to style it green.

I'm aware of ways to handle this with classes, other identifying attributes, or even JavaScript, but is there a pure CSS solution?

Chaosxmk
  • 774
  • 14
  • 28
  • It is possible, but not with css only. – skobaljic Jul 05 '19 at 20:12
  • As in with javascript? – Chaosxmk Jul 05 '19 at 20:13
  • Yes, with server side or client side script. I suggest you add JS/jQuery tag to your question. – skobaljic Jul 05 '19 at 20:16
  • Updated question to clarify that a pure css solution was intended. Just theoretical for now I guess. – Chaosxmk Jul 05 '19 at 20:20
  • The answer is no, css cannot style text nodes, only elements. No reason to keep this question. – skobaljic Jul 05 '19 at 20:25
  • p span { color: blue; } p span:first-child { color: red; } p span:last-child { color: green !important; } – Evik Ghazarian Jul 05 '19 at 20:30
  • @EvikGhazarian the problem with that is that if a span is the only child, it will color itself green, the :nth-child selectors determine their target based off of the surrounding elements, my question refers more to the text surrounding the tags themselves. – Chaosxmk Jul 05 '19 at 20:35
  • realistically if your span appears before any other text it means its the first child and if it appears after all the texts it would be last child. but if your question is something else and you care more about the surrounding text. css cannot determine if the span is surrounded by any text or not. and yes the solution wont work on single span in a paragraph – Evik Ghazarian Jul 05 '19 at 20:38
  • I'll keep the question open in case some day specs come out for supporting something like this. – Chaosxmk Jul 05 '19 at 20:48

0 Answers0