0

I want the background of upperdiv to become red when lowerdiv has the .active class:

<div id="upperdiv">Text case</div>
<div id="lowerdiv" class="active">IMAGE CAROUSEL</div>

.active is being added by JavaScript. Example image.

I tried:

#upperdiv + #lowediv .active {
    background: red;
}

but it's not working.

Is this possible with CSS or jQuery?

dodov
  • 5,206
  • 3
  • 34
  • 65
labediha
  • 1
  • 2
  • I need to see the html structure to be able to assist. I assume its a div with the class `upperDiv` that has a child div with the class `lowerDiv`? – Glen Keane Feb 26 '17 at 09:50
  • There is a `+` selector for next sibling but not the inverse so you can't really do this with pure CSS. – apokryfos Feb 26 '17 at 10:02

2 Answers2

0

If I understand the question correctly you are trying to select the previous sibling. There is no way to do this using CSS. However, using JavaScript you can achieve the desired result. When you add the active class to the lower div, use your script to change the background color of the upper div.

See Is there a "previous sibling" CSS selector? for more information.

Community
  • 1
  • 1
katzkode
  • 1,911
  • 1
  • 13
  • 18
0

First I'd like to warn that OP doesn't ask to hack impossible CSS thing like previous sibling styling. So I'd ask people to read carefully question before downvote or abuse this answer.

There are two ways to get it with CSS, but you can use these ways for specific cases only. Common requirement is that both divs should come one by one.

First way is to swap divs using position attributes. I mean that lower div should come first in your HTML:

<div id="lowerdiv" class="active">IMAGE CAROUSEL</div>
<div id="upperdiv">Text case</div>

div {
  position: absolute;
  width: 100%;
  height: 50px;
  margin: 0;
  left: 0;
  background: orange;
}
#upperdiv {
  margin-top: 0px;

}
#lowerdiv{
  margin-top: 50px;
}

#lowerdiv.active + #upperdiv {
  background: red;
}
<div id="lowerdiv" class="active">IMAGE CAROUSEL</div>
    <div id="upperdiv">Text case</div>

And second way is to use ::before pseudo-element to put it under upperdiv as a background:

div {
  position: relative;
  width: 100%;
  height: 50px;
  margin: 0;
  left: 0;
  background: transparent;
}

#lowerdiv{
  background: orange;
}

#lowerdiv.active:before {
  content: " ";
  display: block;
  position: absolute;
  height: 100%;
  width: 100%;
  bottom: 100%;
  background: red;
  z-index: -1;
}
<div id="upperdiv">Text case</div>
<div id="lowerdiv" class="active">IMAGE CAROUSEL</div>

Third way really exists but this is beyond conditions of the question.

Banzay
  • 9,310
  • 2
  • 27
  • 46