Sprites LESS CSS Variable increment issue

后端 未结 2 1985
猫巷女王i
猫巷女王i 2021-01-15 12:39

I have a problem with sprites background position calculation using a variable:

My code looks something like this:

@counter: 1;

#my-icon-bundle {
.m         


        
2条回答
  •  有刺的猬
    2021-01-15 13:24

    Since a counter based solution seems to still may have some shortcomings depending on possible use-cases (beside the hack-based counter thing itself, see my comment to the corresponding answer) I decided to post a list/loop-based solution I mentioned earlier. I keep the code here as close as possible to the counter-based one so they could be easily compared. (But in general all could be made much clean, structured and generic with further polishing by renaming and reordering all those namespaces/selectors/mixins/variables, removing unnecessary quotes etc.).

    Opt. 1

    When you need only arbitrary icon(s) of the sprite to have its class in the CSS output:

    @row: 1;
    
    // ......
    
    .my-icon-bundle {
        .myIcon(@row, @index) {
            @x: (@row * @index);
            @y: (@row * @index);
            background-position: -@x -@y;
        }
    
        .myIconX(@name) {
            @icons:
                "classX1",
                "classYY1",
                "classZZZ",
                "anotheRR9",
                "etc.";
    
            .find(1);
            .find(@i) when (@name = extract(@icons, @i)) {
                @name_: e(@name);
                .my-icon-@{name_} {
                    #my-icon-bundle.myIcon(@row, @i);
                }
            }
            .find(@i) when not
                (@name = extract(@icons, @i)) {
                    .find((@i + 1));
            }
        }
    }
    
    // ......
    // usage:
    
    #my-icon-bundle.myIconX("anotheRR9");
    #my-icon-bundle.myIconX("classX1");
    

    Opt. 2

    When you just need to generate corresponding classes for all icons in the sprite:

    @row: 1;
    
    // ......
    
    #my-icon-bundle {
        .myIcon(@row, @index) {
            @x: (@row * @index);
            @y: (@row * @index);
            background-position: -@x -@y;
        }
    
        .icons() {
            @icons:
                "classX1",
                "classYY1",
                "classZZZ",
                "anotheRR9",
                "etc.";
    
            .make(length(@icons));
            .make(@i) when (@i > 0) {
                .make((@i - 1));
                @name_: e(extract(@icons, @i));
                .my-icon-@{name_} {
                    #my-icon-bundle.myIcon(@row, @i);
                }
            }
        }
    }
    
    // ......
    // usage:
    
    #my-icon-bundle.icons();
    

    P.S. All this is for LESS 1.5.x, I'm too lazy to make it compatible with earlier versions - sorry.

提交回复
热议问题