multiple nested selectors with variables in Less

后端 未结 3 1377
醉梦人生
醉梦人生 2020-12-20 07:23

I want to build some CSS along these lines:

h1,h2,h3,h4,h5,h6 {some rule}
h1 a,h2 a,h3 a,h4 a,h5 a,h6 a {color: inherit;}
h1 span,h2 span,h3 span,h4 span,h5         


        
3条回答
  •  -上瘾入骨i
    2020-12-20 08:14

    If you have these variables and selectors:

    @headings: h1,h2,h3,h4,h5,h6;
    
    @{headings} {
        some-rule: rule;    
    }
    .headings { // this is a placeholder
        color: inherit;
    }
    h1 span {
        other-rule: rule;
    }
    

    You can use this mixin to generate the code you want:

    .mixin(@headings; @count) when (@count > 0) {
        .mixin(@headings; @count - 1);
        @heading: extract(@headings, @count);
        @{heading}{
            & a:extend(.headings) {}
            & a:extend(h1 span) when not (@heading = h1) {}
        }
    }
    

    Calling:

    .mixin(@headings, length(@headings));
    

    will generate:

    h1, h2, h3, h4, h5, h6 {
      some-rule: rule;
    }
    .headings,
    h1 a,
    h2 a,
    h3 a,
    h4 a,
    h5 a,
    h6 a {
      color: inherit;
    }
    h1 span,
    h2 a,
    h3 a,
    h4 a,
    h5 a,
    h6 a {
      other-rule: rule;
    }
    

提交回复
热议问题