difference between blank and empty pseudo-classes

2019-01-19 21:17发布

问题:

what is the difference between :empty and :blank (CSS Selectors Level 4 draft) ? Other than the fact that blank only works in Firefox as of now.

div div{
  
  width:100px;
  height:100px;
  display:inline-block;
  margin:5px;
  }
div.emptyCell:empty{
  
  background:#009688;
  
  }
div.blankCell:blank{
  
  background:#3F51B5;
  
  }
<div><div class="emptyCell"><!-- nothing but a comment--></div>
<div class="emptyCell"></div>
<div class="emptyCell"><!-- nothing but a comment--></div>
<div class="emptyCell"></div>
  </div>
<div>
<div class="blankCell"></div>
<div class="blankCell"><!-- nothing but a comment--></div>
<div class="blankCell"></div>
<div class="blankCell"><!-- nothing but a comment--></div>
  </div>

回答1:

The :blank pseudo-class builds upon the :empty pseudo-class. Like :empty, :blank will select elements that contain nothing at all, or contain only an HTML comment. But, :blank will also select elements that include whitespace, which :empty will not.

css-tricks :blank

Also, From the W3c Working Draft on selectors level 4:

The :blank pseudo-class is identical to the :empty pseudo-class, except that it additionally excludes characters affected by whitespace processing [CSS3TEXT] when determining whether an element is empty.

Example:

For example, the following element matches :blank, but not :empty, because it contains at least one linebreak, and possibly other whitespace:

<p> 
</p>


回答2:

:empty will match all of the given elements because an element node that contains nothing but comment nodes is essentially the same as an element node with no children as far as CSS is concerned. That is why you're not seeing a difference between matches.

The difference is that :blank matches elements that consist solely of whitespace characters, which are otherwise not considered to be :empty. This is because whitespace nodes are really just text nodes that contain only whitespace, and an element with a text node child is not an empty element.

Important to note however is that the CSSWG is considering changing :empty so that it matches elements that contain only whitespace as well, obviating the need for a separate, and confusingly named, :blank pseudo-class. This was resolved just a few weeks ago. Therefore, :blank as is featured in the current WD may or may not continue to exist in the next WD, which they plan to publish sometime soon seeing as the WD was last updated more than two years ago.

If that does happen, the answer to this question will be:

:blank was an original proposal to Selectors level 4 for matching elements that either have no contents, or only contain whitespace. It has since been removed, and its functionality subsumed into level 4 :empty, obviating the need for a separate, and confusingly named, pseudo-class.