Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
791 views
in Technique[技术] by (71.8m points)

loops - LESS mixin recursion error to convert pixels to rems

I am trying to make a mixin to propery convert pixels to relative ems. I would like it to be flexible enough to allow any property to be used with any number of pixel values.

Any ideas on how to add multiple values to a single property without the recursion error I'm creating inside the for loop?

desired usage example 1:

.pixels-to-rems(font-size; 10);

desired output:

font-size: 10px;
font-size: 1rem;

desired usage example 2:

.pixels-to-rems(padding; 10,0,20,10);

desired output:

padding: 10px, 0px, 20px, 10px;
padding: 1rem, 0px, 2rem, 1rem;

Here's the mixin as is.

@baseFontSize: 10px;
.pixels-to-rems(@property, @pxvals) {
    @pxValue: null;
    @remValue: null;

    .for(@pxvals); .-each(@pxval) {
        @pxValue: @pxValue @pxval;
        @remValue: @remValue (@pxval / @baseFontSize);
    }

    @{property}: ~"@{pxValue}px";
    @{property}: ~"@{remValue}rem";
}

.for() mixin found here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

See Merge feature. The only trick is that the merge statement will concatenate values into the same property rule, thus you'll have to isolate px and rem rules via some hack. For example like this:

usage {
    .pixels-to-rems(padding, 10 0 20 10);
    .pixels-to-rems(font-size, 50);
}

// impl.:

@base-font-size: 10px;

.pixels-to-rems(@p, @vs) {
    .for(@vs); .-each(@v) {
        @{p}+_:     1px  * @v;
        @{p}@{-}+_: 1rem * @v / @base-font-size;
    }
    @-: ~" ";
}

// .for-each impl. (stripped from the snipped linked in the question)

.for(@array)                 {.for-impl_(length(@array))}
.for-impl_(@i) when (@i > 1) {.for-impl_((@i - 1))}
.for-impl_(@i) when (@i > 0) {.-each(extract(@array, @i))}

Demo.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...