1. 面向开发者的 Web 技术
  2. CSS:层叠样式表
  3. CSS 参考
  4. 选择器
  5. :empty

此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。

View in English Always switch to English

:empty

Baseline Widely available *

This feature is well established and works across many devices and browser versions. It’s been available across browsers since ⁨2015年7月⁩.

* Some parts of this feature may have varying levels of support.

:empty CSS 伪类用于选择不包含任何子元素的元素。子元素可以是元素节点或文本(包括空格)。但是注释、处理指令和 CSS content 不会影响元素是否被认定为空。

尝试一下

div:empty {
 outline: 2px solid deeppink;
 height: 1em;
}
<p>Element with no content:</p>
<div></div>
<p>Element with comment:</p>
<div><!-- Simple Comment --></div>
<p>Element with nested empty element:</p>
<div><p></p></div>

备注:选择器 Level 4 中,:empty 伪类被更改为与 :-moz-only-whitespace 类似一样的行为,但目前还没有浏览器支持它。

语法

css
:empty {
 /* ... */
}

示例

HTML

html
<div class="box"><!-- 它将呈现为青柠色。 --></div>
<div class="box">我将会是粉色。</div>
<div class="box">
 <!-- 由于这个注释周围存在空格,所以它将在旧版本的浏览器中呈现为粉色。 -->
</div>
<div class="box">
 <p>
 <!-- 由于这个注释周围存在无法折叠的空格和元素,所以它将在所有浏览器中呈现为粉色。 -->
 </p>
</div>

CSS

body {
 display: flex;
 justify-content: space-around;
}
css
.box {
 background: pink;
 height: 80px;
 width: 80px;
}
.box:empty {
 background: lime;
}

结果

无障碍考虑

辅助技术(如屏幕阅读器)无法解析交互内容为空的情况。所有交互内容必须具有无障碍名称,这是通过为交互控件的父元素(如锚点按钮等)提供文本值来创建的。无障碍名称将交互控件暴露给无障碍树,这是一个传达对辅助技术有用的信息的 API。

提供交互控件的无障碍名称的文本可以使用一些属性的组合进行隐藏,这些属性可以将其在视觉上从屏幕上移除,但可以被辅助技术解析。这通常用于仅依靠图标来传达目的的按钮。

规范

Specification
Selectors Level 4
# the-empty-pseudo

浏览器兼容性

参见

Help improve MDN

Learn how to contribute

This page was last modified on by MDN contributors.

AltStyle によって変換されたページ (->オリジナル) /