2

I'm trying to target the next p block in the following code. While the FOO highlights in yellow, Foo 2 is not highlighting in red, even though my CSS uses the adjacent sibling syntax (+). What could be going wrong here?

<style>
p span.test { background-color: yellow; }
p span.test + p { background-color: red !important; }
</style>


<p>
    <span class="test">Foo</span>
</p>

<p>Foo 2</p>
MacGyver_97
  • 205
  • 2
  • 12

2 Answers2

3

The sibling selector actually is working correctly there. The issue is that the first rule p span.test { background-color: yellow; } is targeting "any span with class test that is inside a p". It's the span that is being made yellow, not the p.

The second p is not a sibling of the span -- int is only a sibling of the other p. So the rule does not apply to it.

Unfortunately, there is no CSS "parent" selector, so you can't easily reverse this. Instead, you would have to put a class on at least one of the p's, like below:

p span.test { background-color: yellow; }
p.first + p { background-color: red; }
<p class="first">
    <span class="test">Foo</span>
</p>

<p>Foo 2</p>
QuinnFreedman
  • 1,664
  • 2
  • 19
  • 34
  • Thank you. While technically your answer is correct, I cannot modify the original code so the first p has to remain without a class. Is there a way to achieve this? – MacGyver_97 Mar 09 '21 at 01:36
  • 1
    It's difficult to say exactly without seeing the whole document. In this toy example, you could use the [`nth-child`](https://www.w3schools.com/cssref/sel_nth-child.asp) selector. You could also definitely achieve this with javascript. I don't know the exact jQuery phrase offhand but I think it would be easy to do something like "select all `span`s inside of `p`s, get their parents, and then get their parents' first siblings." – QuinnFreedman Mar 09 '21 at 01:39
  • Ah yes -- the nth-child helped, as I was able to find an element higher up that let me target the right paragraph! – MacGyver_97 Mar 09 '21 at 01:47
1

The adjacent sibling combinator (+) separates two selectors and matches the second element only if it immediately follows the first element, and both are children of the same parent element.

In your code, the two <p> tags are children of the same parent. but the <span> is a child of <p> tag. So, if we consider the "test" class and next <p> tag, they are not child elements of the same parent. So, that is the reason why your code is not working.

The correct syntax is:

former_element + target_element { style properties }

Therefore your code should be changed as follows:

    <style>
        p span.test { background-color: yellow; }
        p + p { background-color: red; }
    </style>

This works fine.

Pawara Siriwardhane
  • 909
  • 4
  • 11
  • 24