149

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

Nick Ginanto
  • 31,090
  • 47
  • 134
  • 244
  • 1
    There is nothing to fiddle. I just want to add the unit of the number to the calculation. Same as (400/20)px. How do I have a number and px/em/% in scss? That way I could have "global variables" I can change once – Nick Ginanto Nov 13 '12 at 10:56
  • Try to add a bracket like $my_width: ((4/12)%); – Sri Nov 13 '12 at 10:59
  • Oops.. Sorry, I didn't have a chance to check it and give a one more try to do this.. {$my_width: (4/12)%;} – Sri Nov 13 '12 at 11:05

4 Answers4

259

Have you tried the percentage function ?

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

UPDATE

This function was updated since version 1.33.0 and now this is a correct method to do it:

@use "sass:math";

div {
    width: math.percentage(math.div(4,12));
}

Source: https://sass-lang.com/documentation/modules/math#percentage

Jakub Muda
  • 6,008
  • 10
  • 37
  • 56
Tomas
  • 3,573
  • 2
  • 20
  • 25
  • 1
    is there a similar function for px and em? – Nick Ginanto Nov 13 '12 at 11:22
  • 1
    Not sure, but in the source section of the documentation you can see the underlying logic: Sass::Script::Number.new(value.value * 100, ['%']), so I would think that if they do not exist you could do this directly, or create some wrapper functions yourself. – Tomas Nov 13 '12 at 11:26
  • 4
    @NickGinanto for px you can just add `+px` to the end of the line, e.g. `width: ($foo + $bar) +px` – DisgruntledGoat Mar 06 '13 at 21:52
  • 2
    @DisgruntledGoat No, you should **never** do that ever under any circumstance. Adding units should be done via multiplication (eg. `$foo + $bar * 1px`), concatenating the unit on like that only gives you a string. – cimmanon Mar 10 '15 at 01:16
  • @cimmanon did that change recently? I'm sure it wasn't the case when I posted my comment. – DisgruntledGoat Mar 10 '15 at 14:31
  • As far as I am aware, it was never the case. – cimmanon Mar 10 '15 at 14:36
34

Another way:

$my_width: 4/12 * 100%;

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

Sass will output the value in %.

Jakub Muda
  • 6,008
  • 10
  • 37
  • 56
rlejnieks
  • 521
  • 4
  • 8
6

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.

2

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) + '%'};
    }
}