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 :(
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.
To hide an element, set the style display property to “none”. document. getElementById("element").
There is a pseudo class for this: :only-child
(MDN)
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.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With