-1

I'm trying to target a link that ONLY occurs after an image, but they're in separate tags like so:

<p>
  <a href=whatever>
    <img stuff>
  </a>
</p>
<p>
  <a href=something>This should be a different color</a>

This "works":

p + p>a {
  color: red;
}

But it's a bit inspecific. I want to do something like this, but I think it's looking for the sibling of the IMAGE not the PARAGRAPH when I do this:

p>a>img + p>a {
  color:red
}

So the first example works, but might trigger on something I didn't intend. The second doesn't work at all and maybe it can't. I'd love to use classes or ids, but this is in a project using markdown which gets translated to HTML. The only way I have to target elements is by general structure and not attributes (unless you know another way?)

Temani Afif
  • 245,468
  • 26
  • 309
  • 415
not_a_generic_user
  • 1,906
  • 2
  • 19
  • 34

1 Answers1

2

It might be helpful to know that browsers match selectors left to right, and sometimes reading it yourself that way can be helpful. Also, keep in mind that your spacing is implying groupings that CSS does not care about.

So if we read it right to left, we find that this p + p>a would be read as "an anchor inside of a paragraph and that paragraph is itself next to another paragraph".

On the other hand, p>a>img + p>a would be read as "an anchor inside of a paragraph, which is itself next to an image that is inside of an anchor inside of a paragraph." By leaving out spaces between your selectors and > you are implying a grouping that does not exist. So this would actually match like this:

<p>
  <a>
    <img/>
    <p>
      <a>THIS HERE IS WHAT IS TARGETED</a>
    </p>
  </a>
</p>

Obviously this structure is absurd, but you understand I hope the way the targeting is working. There is no way to traverse back up to a parent (there is no < selector), nor can you group selectors like (p>a>img) + (p>a), so unfortunately the selection approach you want here is not feasible/possible.

Alexander Nied
  • 12,804
  • 4
  • 25
  • 45