HTML5 筆記 - :empty Selector

HTML5 筆記 - :empty Selector

通常,在我們的元素裡面,大多都會有文本以及子元素,然而假設今天是完全沒有的,但又想要選取該怎麼辦?這時候就可以使用 :empty 選取器

1
2
3
4
5
<div> </div>
<!-- Not Empty -->

<div></div>
<!-- Empty -->
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
div::before {
content: "not empty";
}

div:empty::before {
content: "empty";
}

div {
color: silver;
}

div:empty {
color: red;
}

https://codepen.io/BeastRush/pen/QWjNqBW

如何定義 empty?

當我第一是看到有人這樣用的時候,其實有點看不太懂是什麼,所以我相信如果你沒看過也還搞不太清楚是如何定義 :empty,先來看看 MDN 的定義:

The :empty CSS pseudo-class represents any element that has no children. Children can be either element nodes or text (including whitespace). Comments, processing instructions, and CSS content do not affect whether an element is considered empty.

Only in Firefox

空白會被視為 empty,:-moz-only-whitespace,但基本上是完全可以忽略的東西,除非真的像工作上遇到 FireFox bug with: rowspan + border-collapse + border 裡面少了 table 的底線,又或者是 Windows APP Outlook 多了 td,但是其他瀏覽器、手機 APP 開通通都正常的情況…

Note: In Selectors Level 4 the :empty pseudo-class was changed to act like :-moz-only-whitespace, but no browser currently supports this yet.

Not Empty

如同開頭的例子及定義,有文本、空白、子元素

1
2
3
4
5
6
7
<div> </div>

<div>
<!-- Comment with whitespace-->
</div>

<div><h1>Chester</h1></div>

Empty

標籤裡面沒有東西(包含空白)及裡面是註解

1
2
<div></div>
<div><!-- Comment but Empty--></div>

實例

1
2
3
4
5
<!-- No error message -->
<p class="error"></p>

<!-- Yes error message -->
<p class="error"> Missing Email</p>
1
2
3
4
5
6
7
.error:before {
color: red;
content: "\02716";
}
.error:empty:before {
display: none;
}

https://codepen.io/BeastRush/pen/QWjNqBW

參考資料