skip to Main Content

Here’s my problem :

I want to do this kinda class in my project (class="h-[2%]"), so i did this little code but something isn’t rigth …

I am not familiar with SCSS so i don’t know why ‘px’ is doing good but ‘%’ is just not …

/* Pixels */
@for $i from 1 through 100 {
    .w-#{$i}px {
        width: #{$i}px
    }
}

/* Purcent */
@for $i from 1 through 100 {
    .w-#{$i}% {
        width: #{$i}%
    }
}

/* Pixels */
@for $i from 1 through 100 {
    .h-#{$i}px {
        height: #{$i}px
    }
}

/* Purcent */
@for $i from 1 through 100 {
    .h-#{$i}% {
        height: #{$i}%
    }
}

I have tried some wierd things like : ‘%’ % ‘%’ ‘%’ but i d’ont think it is the good way to go.

Thanks a lot to the people who will save my day !

2

Answers


  1. Chosen as BEST ANSWER

    I found a way to solve my problem.

    Apparently, you cannot assign a value to a variable that includes a unit of measurement (like %, px, em, ...) directly from a variable interpolation. For this I used another method, then the one I was struggling with :

    @function calculatePercentage($value) {
        @return $value * 1%;
    }
    
    @for $i from 1 through 100 {
        $percentage: calculatePercentage($i);
        .h-#{$i}% {
            height: $percentage;
        }
    }

    Thank you all !


  2. In SCSS, when you’re dealing with percentages, you need to escape the ‘%’ character using a backslash (%).

    /* Pixels */
    @for $i from 1 through 100 {
        .w-#{$i}px {
            width: #{$i}px;
        }
    }
    
    /* Percentages */
    @for $i from 1 through 100 {
        .w-#{$i}% {
            width: #{$i}%;
        }
    }
    
    /* Pixels */
    @for $i from 1 through 100 {
        .h-#{$i}px {
            height: #{$i}px;
        }
    }
    
    /* Percentages */
    @for $i from 1 through 100 {
        .h-#{$i}% {
            height: #{$i}%;
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search