Search code examples
csssyntaxcss-selectorsmatchoperator-precedence

In CSS, is 'div:first-of-type[label="hello"]' different from 'div[label="hello"]:first-of-type'?


In CSS, is this selector:

div:first-of-type[label="hello"]

any different from:

div[label="hello"]:first-of-type

?


Solution

  • Unlike pseudo element, pseudo classes can appear in the middle of a selector:

    Pseudo-classes are allowed in all sequences of simple selectors contained in a selector. Pseudo-classes are allowed anywhere in sequences of simple selectors, after the leading type selector or universal selector (possibly omitted). ref

    So both are the same

    div[label="hello"]:first-of-type {
      height:50px;
    }
    
    
    div:first-of-type[label="hello"] {
      border:5px solid;
    }
    <div label="hello" class="box"></div>


    Considering the new specification:

    Like other simple selectors, pseudo-classes are allowed in all compound selectors contained in a selector, and must follow the type selector or universal selector, if present.


    Worth to note that :first-of-type will only consider the element and its sibling. So the first selector will not select the first div having label=hello but the first div if it has the label=hello.

    In other words, the 2 conditions must be true to select the element that's why the order doesn't matter and both selectors are the same.

    You can see both selectors like below:

    div[label="hello"]:first-of-type
    (div) && (label="hello") && (first of type)
    (div) && (first of type) && (label="hello")
    div:first-of-type[label="hello"] 
    

    Related: Can I combine :nth-child() or :nth-of-type() with an arbitrary selector?