Double ampersand in LESS

后端 未结 1 1320
萌比男神i
萌比男神i 2021-01-13 14:44

I\'m confused about double ampersand behaviour in LESS compiler.

Look:

.heading {
    &&--type-small {
        font-size: 15px;
    }
}
         


        
1条回答
  •  醉梦人生
    2021-01-13 15:41

    What happens when you use an ampersand in a nested rule is that the default nested structure gets ignored in the output selector and the ampersand acts as a placeholder for the complete list of outer selectors and will just insert all the parent rules all the way to the top of the hierarchy (the "path" for all nesting levels above) ... no way around that.

    So using the first one - & will just join (concatenate) the nested selector to the whole list of outer selectors (appearing as if it just added it to the parent selector) and act as a combinator - see "Nested rules" at lescss.org. But then when you use the second ampersand - your selector will end up including all outer rules once again - the .wrapper and all rules in between will be added twice now. So, the behavior is not really strange. See also my answer to this question: "How to refer to two previous elements / tags / classes with LESS?" and for some more functionality of & see also seven-phases-max's comments below. Or find some examples of & being used as a "path" placeholder under "Advanced Usage of &" at lescss.org.

    And to your concrete example:

    I am not completely sure why you want to repeat the word "header" in the class name .header--type-small, if you are using it in addition to a class called .header ... I would just use additional classes such as .type-small, like so:

    .wrapper {
        //style for the wrapper
        .heading{
            //general style for the heading
            &.type-small {
               //style for the heading with class .type-small
               font-size: 15px;
            }
            &.type-large {
               //style for the heading with class .type-large ... and so on
            }
        }
    }
    

    with output CSS:

    .wrapper .heading.type-small {
      font-size: 15px;
    }
    

    but if you really really need the whole long string with the repeated names for some particular reason ... you could just do something like this:

    .wrapper {
        //style for the wrapper
        .heading {
            //general style for the heading
            &.heading--type{
                &-small {
                   //style for the heading with class .type-small
                   font-size: 15px;
                }
            }
        }
    }
    

    with output CSS:

    .wrapper .heading.heading--type-small {
        font-size: 15px;
    }
    

    0 讨论(0)
提交回复
热议问题