skip to Main Content

I have a situation similar to this:

On first page of a website

<div class="div1">

 <div class="child"> </div>
</div>

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

On some other pages:


<div class="div1">

<div class="child"> </div>
<div class="child"> </div>
<div class="child"> </div>
</div>

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

Basically, I want to hide div2 only for a div that has only one child.

I can use only CSS.

Is it possible to target only that specific one child div and hide "div2" using only CSS?

Thanks

What I recall is that I tried doing something similar in the past for div that had 6 children.

(changing width)

/* six items */
div.answer:first-child:nth-last-child(6),
div.answer:first-child:nth-last-child(6) ~ div {
width: calc(50% - 14px) !important;
}

The trick was that we influence the first child and all of its siblings when the first child was also the sixth child from the end.

2

Answers


  1. you can use :has() Pseudo Class for this effect.

    .div1:has( .child:only-child ) + div2 {
        display: none;
    }
    

    For more study about :has pseudo class, you can use this link.

    Login or Signup to reply.
  2. As of today there is

    No all browser supported method for this

    Firefox still doesn’t natively supports :has() by default. (not recommended)

    For this to actually work, you will have to modify your HTML a little.
    All you will have to do is to make the .div2 a child of .div1 and then this css should do the trick:

    .child + .div2:not(.child + .child + .div2){
    background-color: pink;
    }

    It selects a .div2 class which is a sibling of .child class but not is a sibling of .child class which is a sibling of another .child class.

    This simplifies to selecting a .div2 class with only one .child class.

    Code snippet:

    .child + .div2:not(.child + .child + .div2){
      background-color: pink;
    }
    <div class="div1">
      <div class="child">first</div>
      <div class="child">second</div>
      <div class="child">third</div>
      <div class="div2">div2</div>
    </div>
    
    
    <div class="div1">
      <div class="child">first</div>
      <div class="div2">div2</div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search