1

I'm having trouble selecting a particular em element. I have a block which looks like this which I use for photos on my blog:

<p>
    <em><img /></em>
    <em>This is the element I'd like to select and style.</em>
</p>

I'm trying to use CSS to select the second em element. I know I can use the adjacent sibling combinator: em + em.

Unfortunately this also selects every other instance of two italicized groups of text, a situation which comes up fairly regularly (and which I'm currently preventing by putting empty blocks between adjacent groups of italicized text).

My suspicion is that this might be possible given the fact that one em element always contains an img element, but I'm not sure.

Without using classes or IDs (as this is originally written in markdown and processed by GitHub Pages), is there another way to select and style that second em tag?

Not a duplicate: Were I trying to select the child of the first em element, then yes, this would be a duplicate. But I'm trying to select the second em element, and can't rely on selecting every single child em with a p element as its parent.

Temani Afif
  • 180,975
  • 14
  • 166
  • 216
Alex Johnson
  • 918
  • 6
  • 22
  • You would need to find *some* point of uniqueness. That can even be the `nth-of-type` on the `p` tag if need be. You would need to provide more code for us to help craft that selection logic for you. – Obsidian Age Jan 29 '19 at 00:30
  • The challenge with nth of type, at least as far as the p tag goes, is that there may be 1 image on the page or 10. Just depends on the the post. – Alex Johnson Jan 29 '19 at 01:04
  • @temani-afif Can you reconsider marking this as a duplicate? The question you linked to is unrelated. – Alex Johnson Jan 29 '19 at 22:37
  • it's the same because you need to first select the *first* em then use `+` .. you will need then two selector, a parent selector and a sibling selector. The first one is not possible thus the duplicate – Temani Afif Jan 29 '19 at 22:42
  • here is the selector you need `em:has(> img) + em` .. the first part is not yet supported as said in the duplicate – Temani Afif Jan 29 '19 at 22:42
  • and the duplicate give you the way to do with JS/jQuery if you want also. As a side note, the parent here is the `em` not the `p` like you added at the end of the answer – Temani Afif Jan 29 '19 at 22:46
  • Are the two em tags not siblings? I'm trying to select the second of those two siblings. In any case, thanks for the explanation. – Alex Johnson Jan 30 '19 at 02:32

0 Answers0