Calculate a percent with SCSS/SASS

CssSass

Css Problem Overview


I want to set a width in percentage in scss via calculation, but it gives me errors..

> Invalid CSS after "...-width: (4/12)%": expected expression (e.g. 1px, > bold), was ";"

I want to do something like

$my_width: (4/12)%;

div{
width: $my_width;
}

how do I add the % sign in there?

Same question with px and em

Css Solutions


Solution 1 - Css

Have you tried the percentage function ?

$my_width: percentage(4/12);
div{
width: $my_width;
}

Solution 2 - Css

Another way:

$my_width: 4/12*100%;

div{
width: $my_width; // 33.33333%
}

Sass will output the value in %.

Solution 3 - Css

I was able to make it work this way:

div{
   width: (4/12)* 1%;
   }

This way you don't need to use any special function.

Solution 4 - Css

If you wanna use a loop, maybe this solution will be working

@for $i from 1 through 12 {
    .col-#{$i} {
        width: #{calc(100 * $i / 12) + '%'};
    }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNick GinantoView Question on Stackoverflow
Solution 1 - CssTomasView Answer on Stackoverflow
Solution 2 - CssrlejnieksView Answer on Stackoverflow
Solution 3 - CssEnrique CuchettiView Answer on Stackoverflow
Solution 4 - CssRashad YusifovView Answer on Stackoverflow