使用纯CSS隐藏一个元素的列表 [英] Hide list with one element with pure CSS
问题描述
如果仅使用CSS仅包含一个元素,是否有一种隐藏列表的方法?奖金:想想IE8
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>
但是:
<ul>
<li>show this</li>
<li>and others...</li>
</ul>
我在和所有兄弟姐妹和下一个选择器(~
+
)一起玩,但是无法选择上一个CSS元素:(
I was playing with all siblings and next selectors (~
+
) but there is no way to select previous CSS 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)
这也是上述MDN文章的摘录:
Also here is an excerpt from the above MDN article:
:only-child
CSS伪类表示任何元素,它们是 其父母的独生子.与:first-child:last-child
相同 或:nth-child(1):nth-last-child(1)
,但特异性较低.
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:如您在MDN中所见浏览器支持 -IE8不支持此功能,因此对于IE8,您对于纯CSS解决方案是不走运的.
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.
这篇关于使用纯CSS隐藏一个元素的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!