0

I've searched for hours but can't seem to figure out how to target an element that occurs behind another, rather than in front of.

The css + selector targets an element in front of another.

Example:

HTML:

<div class="apples"></div>
<div class="bananas"></div>

CSS:

.apples + .bananas {
    background-color: blue;
}

This will turn the bananas class blue but I want to be able to target the apples class using the bananas class. Seems like the adjacent sibling combinator can't accomplish this. This seems like a mind-bogglingly simple thing to do but there doesn't seem to be an answer for this online. Any help?

What I've tried: I tried using the adjacent sibling combinator and swapping around the target and the base element but this doesn't work:

HTML:

<div class="apples"></div>
<div class="bananas"></div>

CSS:

.bananas + .apples {
    background-color: blue;
}

I'm trying to only add style to an adjacent element that occurs directly before another element based on what classes exist in the the base element. So I only want to add styling to the elements that contain the apples class based on whatever other classes exist in elements that contain the bananas class.

  • Is there a reason this has to depend on a sibling element, rather than simply styling `.bananas { background-color: blue; }`? Please consider that you may have simplified your problem a little too much. – David Thomas Jan 04 '23 at 15:33
  • Could you include enough HTML in the question (preferably create a runnable snippet) as what you can do with bananas might depend on what else you have in the way of container parent etc. Also, is it just the background you want to change or are there other things? See https://stackoverflow.com/help/minimal-reproducible-example – A Haworth Jan 04 '23 at 15:42

0 Answers0