Whitespace in CSS selectors

2019-02-18 06:18发布

In the selector a space can indicate a descendant. However, I see spaces can also be ignored.

From my testing, here is what I think it means:

  • Spaces may be used around , and contextual characters (such as + and >).
  • Spaces may not be used around pseudo class and element characters (: and ::) as well as attribute selectors ([…]).
  • Spaces may not be used with class and id characters (. and #).
  • Spaces inside a "string" are significant.
  • All other spaces are ignored. This includes padding inside an attribute selector.

The question is (a) is this officially correct? and (b) where is this covered?

1条回答
Emotional °昔
2楼-- · 2019-02-18 06:27

All of your conclusions are correct. There are nuances with regard to whitespace in attribute selectors, covered in my answer to this question.

All the exact rules of where whitespace may or may not appear are covered in the grammar. For the purposes of the grammar, the "contextual characters (such as + and >)" that you refer to are officially known as combinators. (The term "contextual selector" was first used in CSS1 but hasn't appeared since.)

Remember in addition that any number of contiguous whitespace characters that separate two simple selectors is considered a descendant combinator, which is in fact one reason why whitespace isn't "allowed" around the delimiters for pseudo-elements, pseudo-classes, attribute selectors, class selectors and ID selectors — because it has significance and therefore its presence alters the meaning of the selector.

查看更多
登录 后发表回答