:父元素的空选择器 [英] :empty selector for parent element
问题描述
我有一个 div
与头元素和 ul
其中我加载 li
项目:
I have a div
with a header element and a ul
in which I load li
items:
<div class="listContainer">
<header>Title</header>
<ul class="list">
<li>Test Element</li>
<li>Test Element</li>
<li>Test Element</li>
</ul>
</div>
在这种情况下,整个 .listContainer
需要
In this case the whole .listContainer
needs to be visible.
但是可以使用CSS :empty
选项来隐藏整个容器,如果 .list
为空,如下所示:
But is it possible to hide the whole container with the CSS :empty
selector, if .list
is empty, like this:
<div class="listContainer">
<header>Title</header>
<ul class="list">
</ul>
</div>
现在我使用:empty
selector隐藏 ul
,但是整个 .listContainer
需要隐藏。
Right now I'm using the :empty
selector to hide the ul
, but the whole .listContainer
needs to be hidden.
.list:empty { display: none; }
我知道这是可能的JavaScript,但在这种情况下,我需要使用CSS但我不知道这是否可能。
I know that it is possible with JavaScript, but in this case I need to do it with CSS alone, but I am not sure if this is possible.
推荐答案
我能提供的最好的父选择器的CSS),是将您的HTML重组到以下:
The best I can offer (bearing in mind that there is no parent-selector for CSS), is to reorganise your HTML to the following:
<div class="listContainer">
<ul class="list"></ul>
<header>Title</header>
</div>
<div class="listContainer">
<ul class="list">
<li>Non-empty</li>
</ul>
<header>Title</header>
</div>
并使用以下CSS:
.listContainer {
position: relative;
border: 2px solid #000;
}
.listContainer header {
position: absolute;
top: 0;
left: 0;
right: 0;
}
.listContainer .list {
margin-top: 2em;
}
.list:empty,
.list:empty + header {
display: none;
height: 0;
margin: 0;
overflow: hidden;
}
不幸的是,这需要一些丑陋的黑客来定位
元素,并且不会精确隐藏 .listContainer
(因为,这是不可能基于子元素)
This does, unfortunately, require some ugly hacking to position the header
element, and doesn't precisely hide the .listContainer
(since, again, this isn't possible based upon a child element), however it does approximate your requirement.
使用与上述相同的HTML,但使用弹性框模型(目前,在此时间和日期,在Webkit中实现)重新排序元素的显示,从而避免位置:绝对
丑陋:
With the same HTML as above, but using the flex-box model (as currently, as of this time and date, implemented in Webkit) to reorder the elements' display, and thus avoid the position: absolute
ugliness:
.listContainer {
border: 1px solid #000;
display: -webkit-flex;
-webkit-flex-direction: column;
-webkit-flex-wrap: nowrap;
}
.listContainer header {
display: -webkit-flex-block;
-webkit-order: 1;
-webkit-flex: 1 1 auto;
}
.listContainer .list {
display: -webkit-flex-block;
-webkit-flex-direction: column;
-webkit-order: 2;
-webkit-flex: 1 1 auto;
}
.listContainer .list:empty,
.listContainer .list:empty + header {
width: 0;
height: 0;
margin: 0;
padding: 0;
overflow: hidden;
display: none;
}
这篇关于:父元素的空选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!