CSS Selecting the next element that follows

Viewed 127

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>
2 Answers

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>

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.

Related