0

I was wondering if it is possible to style a div if a other div contains a specific class?! I know this can be done with jQuery but I was wondering if it can be done with CSS aswell.

Let's say I have

<div class="stickyWrap sticky"></div>
<div class="checkout "></div>

Is it possible to style checkout when stickWrap contains the class sticky?

I tried something like:

.stickyWrap[class*="sticky"] + .checkout{
  background-color: #1f6053; 
}

That obvious doesn't work.

Meules
  • 1,140
  • 4
  • 20
  • 60

3 Answers3

1

Just chain the classnames in the selector.

.stickyWrap.sticky + .checkout {
  background:red;
}
<div class="stickyWrap">not sticky</div>
<div class="checkout ">checkout</div>

<div class="stickyWrap sticky">sticky</div>
<div class="checkout ">checkout</div>

Note: I think the selector you actually wanted was:

.stickyWrap[class$="sticky"] + .checkout{
  background-color: #1f6053; 
}

This will find parent elements that have both .stickyWrap and classes that end in "sticky"...otherwise it's too broad.

JSfiddle Demo

Paulie_D
  • 95,305
  • 9
  • 106
  • 134
0

No need to treat the class as an attribute; you can just select it as, well, a class! Like so:

.stickyWrap.sticky + .checkout{
  background-color: #1f6053; 
}
Hayden Schiff
  • 3,007
  • 15
  • 36
  • `other div contains a specific class` what if the classes are like `class="stickyWrap stickybomb"` – Rajaprabhu Aravindasamy Aug 07 '15 at 18:30
  • I don't understand how that's different. Just use the selector `.stickyWrap.stickybomb + .checkout`. You can chain classes for the same element as much as you want. – Hayden Schiff Aug 07 '15 at 18:31
  • I think the OP's case is like he want to select elements which contains the word sticky in the second class. not the exact word. Am i right? – Rajaprabhu Aravindasamy Aug 07 '15 at 18:34
  • Ah, you might be right. If that's the case, I'd recommend OP change how their classes are added, as that approach is kind of contrary to how CSS classes are best utilized. Every time they add a class that contains the word "sticky", they could also add the class "sticky" itself. – Hayden Schiff Aug 07 '15 at 18:41
-1

Since you have tagged jquery,so give this a go.

if($(".stickyWrap").hasClass("sticky"))
{
   $(".checkout ").css("background-color","#1f6053");
}
Varun
  • 1,950
  • 2
  • 8
  • 16