Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide list with one element with pure CSS

Is there a way to hide list if it contains only one element using just CSS? Bonus: think of IE8

<ul>
  <li>hide this</li>
<ul>

But:

<ul>
  <li>show this</li>
  <li>and others...</li>
</ul>

I was playing with all siblings and next selectors (~ +) but there is no way to select previous CSS element :(

like image 374
Szymon Toda Avatar asked Aug 11 '14 08:08

Szymon Toda


People also ask

How do I hide a list item in CSS?

You can hide an element in CSS using the CSS properties display: none or visibility: hidden . display: none removes the entire element from the page and mat affect the layout of the page. visibility: hidden hides the element while keeping the space the same.

How do you hide an element in HTML?

To hide an element, set the style display property to “none”. document. getElementById("element").


2 Answers

There is a pseudo class for this: :only-child (MDN)

So if I have the following CSS

li:only-child {
    display: none;
}

.. the list items will only be displayed if there is more than one list item.

FIDDLE

(Note: Like Quentin said, it doesn't hide the actual list - just the list item when it is the only child... but as long as the list itself doesn't have its own styling this would be the same as hiding the list)

Also here is an excerpt from the above MDN article:

The :only-child CSS pseudo-class represents any element which is the only child of its parent. This is the same as :first-child:last-child or :nth-child(1):nth-last-child(1), but with a lower specificity.

PS: As you can see from MDN Browser support - IE8 doesn't support this, so for IE8 you're out of luck for a pure CSS solution.

like image 171
Danield Avatar answered Sep 18 '22 06:09

Danield


You can't hide the list, but if the list item is is the only child, then it is both the first and last child, so you can hide that with:

li:first-child:last-child { display: none; }
like image 35
Quentin Avatar answered Sep 22 '22 06:09

Quentin