What is the difference between * and *|* in CSS?

前端 未结 3 1395
广开言路
广开言路 2020-12-12 14:10

In CSS, * will match any element.

Frequently, *|* is used instead of * to match all elements. This is generally used for testi

3条回答
  •  被撕碎了的回忆
    2020-12-12 14:39

    As per W3C Selector Spec:

    The universal selector allows an optional namespace component. It is used as follows:

    ns|*
    all elements in namespace ns

    *|*
    all elements

    |*
    all elements without a namespace

    *
    if no default namespace has been specified, this is equivalent to *|*. Otherwise it is equivalent to ns|* where ns is the default namespace.

    So, no * and *|* are not always the same. If a default name space is provided then * selects only elements that are part of that namespace.


    You can visually see the differences using the below two snippets. In the first, a default namespace is defined and so the * selector applies the beige colored background only to the element which is part of that namsepace whereas the *|* applies the border to all elements.

    @namespace "http://www.w3.org/2000/svg";
    
    * {
      background: beige;
    }
    *|* {
      border: 1px solid;
    }
    This is some link
    
    
      
        This is some link
      
    

    In the below snippet no default namespace is defined and so both * and *|* applies to all elements and so all of them get both the beige background and the black border. In other words, they work the same way when no default namespace is specified.

    * {
      background: beige;
    }
    *|* {
      border: 1px solid;
    }
    This is some link
    
    
      
        This is some link
      
    


    As BoltClock points out in comments (1,2), initially namespaces applied only to XML based languages such as XHTML, SVG etc but as per latest specs, all HTML elements (that is, elements in the HTML namespace) are namespaced to http://www.w3.org/1999/xhtml. Firefox follows this behavior and it is consistent across all HTML5 user agents. You can find more information in this answer.

提交回复
热议问题