-1

Consider these scenarios:

Scenario 1:

<div> 
  <Button class="button"/>
  <div class="div1" />
  <div class="div2" />
  <div class="div3" />
</div>

Scenario 2:

<div> 
  <div class="div1" />
  <div class="div2" />
  <div class="div3" />
</div>

I want to write a css selector for div3 only when its <button>sibling is not present i.e. for Scenario 2.

Is that possible?

AnkitD
  • 66
  • 8

4 Answers4

1

Update the code to include both scenarios.

div > *:first-child:not(Button) ~ div.div3 {
  background: skyblue;
}
<div>
  <Button class="button"> Show Button </Button>
  <div class="div1"> Show Button div1 </div>
  <div class="div2"> Show Button div2 </div>
  <div class="div3"> Show Button div3 </div>
</div>

<div>
  <div class="div1"> div1 </div>
  <div class="div2"> div2 </div>
  <div class="div3"> div3 </div>
</div>
yinsweet
  • 2,823
  • 1
  • 9
  • 21
0

if you want to use class selector in particular you can do:

div .div3 {
  background: red;
}
div .button ~ .div3 {
  background: none;
}
with Button
<div> 
  <button class="button"></button>
  <div class="div1" >div1</div>
  <div class="div2"> div2</div>
  <div class="div3" >div3</div>
</div>
    <br><br>
without Button
<div> 
  <div class="div1" >div1</div>
  <div class="div2"> div2</div>
  <div class="div3" >div3</div>
</div>
Karl L
  • 1,645
  • 1
  • 7
  • 11
  • Actually, I want to use general sibling selector, but i want to style class "div3" only when button is NOT present in the parent div. Something with a combination of :not and sibling is what I am looking for – AnkitD Jun 03 '20 at 03:41
  • Ive edited my answer, hope that helps – Karl L Jun 03 '20 at 03:54
0

You can use :not()

div:not(button) > div{
  background-color:red;
}
<div> has-button
  <Button class="button"/>
  <div class="div1" />
  <div class="div2" />
  <div class="div3" />
</div>

<div> no-button
  <div class="div1" />
  <div class="div2" />
  <div class="div3" />
</div>
norcal johnny
  • 2,050
  • 2
  • 13
  • 17
  • Can you please rephrase the same answer when every div has a seperate class name? Lets say parent div has class="parent-div" – AnkitD Jun 03 '20 at 03:37
  • its the same no matter. it is saying if any div that has child divs and not button in the parent div change background as in my example. – norcal johnny Jun 03 '20 at 03:44
  • `div:not(button)` makes no sense. You're saying select all divs that aren't buttons – j08691 Jun 03 '20 at 03:57
0
<!DOCTYPE html>
<html>
<head>
     <style>
         button ~ .div3 {
                background-color: yellow;
         }
     </style>
</head>
<body>
</html>

   <div> 
      <Button class="button">vv</button>
      <div class="div1" >1</div>
      <div class="div2" >2</div>
      <div class="div3" >4</div>
  </div>

</body>