Libon

CSS :empty 伪类选择器

2 分钟 #CSS
使用 CSS :empty 伪类来增强页面展示效果

ToC

兼容性

它的兼容性还是不错的,主流浏览器最低也能兼容到 IE9

Figure Element

HTML 上有一个元素叫 <figure> 它提供了使用 <figcaption> 元素添加标题的能力,在有些情况下,我们希望标题保留为空,或者是这张图本身就没有标题,但这时候会让页面看起来很糟糕。那这个时候就可以使用 :empty 来隐藏它:

1
<figure>
2
<img src="hello.jpg" />
3
<figcaption></figcaption>
4
</figure>
1
figcaption {
2
padding: 1em;
3
background: #ccc;
4
}
5
6
// 如果元素为空则隐藏它
7
figcaption:empty {
8
display: none;
9
}

Message

还有就是我们页面中经常会用到的一些提示消息,有时候提示消息会同时包含标题和内容,但有的时候只有标题,而标题和正文之间往往会包含一间隔,在项目中我们可能会去判断内容是否为空,如果为空则不渲染内容元素,这原本需要 JS 来操作,但现在我们使用 :empty 伪类就可以做到。

1
<div class="message">
2
<h2>提示信息</h2>
3
<p>这是提示信息内容</p>
4
</div>
5
6
<div class="message">
7
<h2>是否确定删除?</h2>
8
<p></p>
9
</div>
1
.message {
2
border: 1px solid #ccc;
3
background: #f5f5f5;
4
border-radius: 5px;
5
padding: 10px 15px;
6
margin-bottom: 10px;
7
}
8
9
h2 {
11 collapsed lines
10
margin: 0;
11
font-size: 18px;
12
}
13
14
p {
15
margin: 5px 0 0;
16
}
17
18
p:empty {
19
display: none
20
}

而且不仅仅可以作用于空元素的本身,还可以利用 css 选择器的能力作用于其他兄弟元素、后代元素等。比如说搭配上 :not() 或是 + 选择器可以实现只有在没有提示内容的时候才出现关闭按钮:

1
<div class="message">
2
<h2>提示信息</h2>
3
<p>这是提示信息内容</p>
4
<button>关闭</button>
5
</div>
6
<div class="message">
7
<h2>是否确定删除?</h2>
8
<p></p>
9
<button>关闭</button>
1 collapsed line
10
</div>
1
.message {border:1px solid #ccc;background:#f5f5f5;border-radius:5px;padding:10px 15px;margin-bottom:10px}
2
h2 {margin:0;font-size: 18px;}
3
p {margin: 5px 0 0}
4
p:empty {display:none}
5
button {display:none}
6
p:empty + button {display:block}

以上。


CD ..
接下来阅读
Modern CSS Reset