Show only if there are more than 2 children

Is it possible to change the css to show the field only if there are more than two children?

Example:

// Don't show
<ul>
  <li>Something</li>
</ul>

// Show
<ul>
  <li>Something</li>
  <li>Something</li>
</ul>

      

I am trying to do this with CSS only. Is it possible?

+3


source to share


2 answers


You can use a selector :only-child

and hide the li if it's the only one.

ul li:only-child{
  display: none;
}

      

ul li:only-child {
  display: none;
}
      

<ul>
  <li>Don't Display</li>
</ul>
<ul>
  <li>Display</li>
  <li>Display</li>
</ul>
      

Run codeHide result


https://jsfiddle.net/90kx009u/




Here's the JS if you want to accomplish exactly what you ask:

let thelist = document.querySelector('.thelist')

if(thelist.childElementCount <= 1){
    thelist.remove()
}

      

https://jsfiddle.net/90kx009u/2/

+7


source


You cannot directly "count" the total number of elements in CSS, so there is no way to apply the class only if there are 2 or more divs (you need JavaScript for this) See more here: How to add CSS if an element contains more than one child?



+1


source







All Articles