Append unit type to the result of a calculation
up vote
43
down vote
favorite
I've been refactoring my CSS to a SASS style sheet recently. I'm using the Mindscape Web Workbench extension for VS2012, which re-generates the CSS each time you save your SCSS. I started with code similar to this:
/* Starting point: */
h1 { font-size: 1.5em; /* 24px ÷ 16px */ }
Then I tried to refactor it first to this:
/* Recfator: */
h1 { font-size: (24px / 16px)em; }
But this unfortunately produces:
/* Result: */
h1 { font-size: 1.5 em; } /* doesn't work, gives "1.5 em" */
Notice the extra space, which I don't want there. I've tried several alternatives, here are a few:
h1 { font-size: (24/16)em; } /* doesn't work, gives "1.5 em" */
h2 { font-size: 24 / 16em; } /* doesn't work, gives "24/16em" */
h3 { font-size: (24px / 16px) * 1em; } /* works but "* 1 em" feels unnecessary */
h4 { font-size: (24em) / 16; } /* works, but without "px" it's not
really conveying what I mean to say */
I've also tried these variants with variables (because I want those anyways), but that didn't change the situation much. To keep the examples in this question sleek I've left out variables. However, I'd happily accept a solution that relies on using variables (in a clean way).
I've gone through the relevant SASS documenation on '/', and appreciate that this is a tough one for SASS because the '/' character already has a meaning in basic CSS. Either way, I was hoping for a clean solution. Am I missing something here?
PS. This blogpost does offer one solution, using a user defined function. That seems a bit heavy-weight though, so I'm interested if there's "cleaner" solutions in line with my attempts above. If someone can explain the "function approach" is the better (or even only) solution then I'll accept that as an answer too.
PS. This related question seems to be about the same thing, though that one specically wants to do further calculations. The accepted answer there is my third workaround (multiplying by 1em
), but I'd love to know if there's a different (cleaner) way if I'm willing to forego the ability to do further calculations. Perhaps the method mentioned in said question ("interpolation") is useful for me?
Bottom line: how can you cleanly append the unit type (e.g. em
) to the result of a calculation in SASS?
css sass
|
show 7 more comments
up vote
43
down vote
favorite
I've been refactoring my CSS to a SASS style sheet recently. I'm using the Mindscape Web Workbench extension for VS2012, which re-generates the CSS each time you save your SCSS. I started with code similar to this:
/* Starting point: */
h1 { font-size: 1.5em; /* 24px ÷ 16px */ }
Then I tried to refactor it first to this:
/* Recfator: */
h1 { font-size: (24px / 16px)em; }
But this unfortunately produces:
/* Result: */
h1 { font-size: 1.5 em; } /* doesn't work, gives "1.5 em" */
Notice the extra space, which I don't want there. I've tried several alternatives, here are a few:
h1 { font-size: (24/16)em; } /* doesn't work, gives "1.5 em" */
h2 { font-size: 24 / 16em; } /* doesn't work, gives "24/16em" */
h3 { font-size: (24px / 16px) * 1em; } /* works but "* 1 em" feels unnecessary */
h4 { font-size: (24em) / 16; } /* works, but without "px" it's not
really conveying what I mean to say */
I've also tried these variants with variables (because I want those anyways), but that didn't change the situation much. To keep the examples in this question sleek I've left out variables. However, I'd happily accept a solution that relies on using variables (in a clean way).
I've gone through the relevant SASS documenation on '/', and appreciate that this is a tough one for SASS because the '/' character already has a meaning in basic CSS. Either way, I was hoping for a clean solution. Am I missing something here?
PS. This blogpost does offer one solution, using a user defined function. That seems a bit heavy-weight though, so I'm interested if there's "cleaner" solutions in line with my attempts above. If someone can explain the "function approach" is the better (or even only) solution then I'll accept that as an answer too.
PS. This related question seems to be about the same thing, though that one specically wants to do further calculations. The accepted answer there is my third workaround (multiplying by 1em
), but I'd love to know if there's a different (cleaner) way if I'm willing to forego the ability to do further calculations. Perhaps the method mentioned in said question ("interpolation") is useful for me?
Bottom line: how can you cleanly append the unit type (e.g. em
) to the result of a calculation in SASS?
css sass
What does doing the math gain you (other than slower compilation and arguably lower readability)? Not every browser starts with a 16px font-size (historically, Opera used a smaller base font-size than other browsers... and users have been known to increase or decrease their font-size on purpose).
– cimmanon
Dec 16 '12 at 21:26
Once I replace the numbers with variables, the math will show meaning and/or intention, making it self-documenting instead of "magic". As I mention in the question, I left out variables in my examples to keep them simple.
– Jeroen
Dec 16 '12 at 21:39
You still haven't answered the question: what does doing the math gain you? Regardless of what you ultimately use (variables vs hard coded values)24px / 16px * 1em
has lower readability than1.5em
.
– cimmanon
Dec 16 '12 at 21:49
1
You have done a great disservice to Sass authors everywhere by reopening this question. It is now the top result on Google. Your "preferred method" is the worst possible way to append a unit to a number and only causes confusion when it doesn't work the way they expect down the road.
– cimmanon
Jun 26 '15 at 12:55
1
If you disagree with the most upvoted and accepted answer you should write a better answer, not rant in comments about it. - Explain why/when interpolation is the wrong tool of choice and/or tell folks one of the methods I mentioned already is the preferred way.
– Jeroen
Jun 30 '15 at 7:26
|
show 7 more comments
up vote
43
down vote
favorite
up vote
43
down vote
favorite
I've been refactoring my CSS to a SASS style sheet recently. I'm using the Mindscape Web Workbench extension for VS2012, which re-generates the CSS each time you save your SCSS. I started with code similar to this:
/* Starting point: */
h1 { font-size: 1.5em; /* 24px ÷ 16px */ }
Then I tried to refactor it first to this:
/* Recfator: */
h1 { font-size: (24px / 16px)em; }
But this unfortunately produces:
/* Result: */
h1 { font-size: 1.5 em; } /* doesn't work, gives "1.5 em" */
Notice the extra space, which I don't want there. I've tried several alternatives, here are a few:
h1 { font-size: (24/16)em; } /* doesn't work, gives "1.5 em" */
h2 { font-size: 24 / 16em; } /* doesn't work, gives "24/16em" */
h3 { font-size: (24px / 16px) * 1em; } /* works but "* 1 em" feels unnecessary */
h4 { font-size: (24em) / 16; } /* works, but without "px" it's not
really conveying what I mean to say */
I've also tried these variants with variables (because I want those anyways), but that didn't change the situation much. To keep the examples in this question sleek I've left out variables. However, I'd happily accept a solution that relies on using variables (in a clean way).
I've gone through the relevant SASS documenation on '/', and appreciate that this is a tough one for SASS because the '/' character already has a meaning in basic CSS. Either way, I was hoping for a clean solution. Am I missing something here?
PS. This blogpost does offer one solution, using a user defined function. That seems a bit heavy-weight though, so I'm interested if there's "cleaner" solutions in line with my attempts above. If someone can explain the "function approach" is the better (or even only) solution then I'll accept that as an answer too.
PS. This related question seems to be about the same thing, though that one specically wants to do further calculations. The accepted answer there is my third workaround (multiplying by 1em
), but I'd love to know if there's a different (cleaner) way if I'm willing to forego the ability to do further calculations. Perhaps the method mentioned in said question ("interpolation") is useful for me?
Bottom line: how can you cleanly append the unit type (e.g. em
) to the result of a calculation in SASS?
css sass
I've been refactoring my CSS to a SASS style sheet recently. I'm using the Mindscape Web Workbench extension for VS2012, which re-generates the CSS each time you save your SCSS. I started with code similar to this:
/* Starting point: */
h1 { font-size: 1.5em; /* 24px ÷ 16px */ }
Then I tried to refactor it first to this:
/* Recfator: */
h1 { font-size: (24px / 16px)em; }
But this unfortunately produces:
/* Result: */
h1 { font-size: 1.5 em; } /* doesn't work, gives "1.5 em" */
Notice the extra space, which I don't want there. I've tried several alternatives, here are a few:
h1 { font-size: (24/16)em; } /* doesn't work, gives "1.5 em" */
h2 { font-size: 24 / 16em; } /* doesn't work, gives "24/16em" */
h3 { font-size: (24px / 16px) * 1em; } /* works but "* 1 em" feels unnecessary */
h4 { font-size: (24em) / 16; } /* works, but without "px" it's not
really conveying what I mean to say */
I've also tried these variants with variables (because I want those anyways), but that didn't change the situation much. To keep the examples in this question sleek I've left out variables. However, I'd happily accept a solution that relies on using variables (in a clean way).
I've gone through the relevant SASS documenation on '/', and appreciate that this is a tough one for SASS because the '/' character already has a meaning in basic CSS. Either way, I was hoping for a clean solution. Am I missing something here?
PS. This blogpost does offer one solution, using a user defined function. That seems a bit heavy-weight though, so I'm interested if there's "cleaner" solutions in line with my attempts above. If someone can explain the "function approach" is the better (or even only) solution then I'll accept that as an answer too.
PS. This related question seems to be about the same thing, though that one specically wants to do further calculations. The accepted answer there is my third workaround (multiplying by 1em
), but I'd love to know if there's a different (cleaner) way if I'm willing to forego the ability to do further calculations. Perhaps the method mentioned in said question ("interpolation") is useful for me?
Bottom line: how can you cleanly append the unit type (e.g. em
) to the result of a calculation in SASS?
css sass
css sass
edited May 23 '17 at 12:26
Community♦
11
11
asked Dec 16 '12 at 20:56
Jeroen
34.9k22118187
34.9k22118187
What does doing the math gain you (other than slower compilation and arguably lower readability)? Not every browser starts with a 16px font-size (historically, Opera used a smaller base font-size than other browsers... and users have been known to increase or decrease their font-size on purpose).
– cimmanon
Dec 16 '12 at 21:26
Once I replace the numbers with variables, the math will show meaning and/or intention, making it self-documenting instead of "magic". As I mention in the question, I left out variables in my examples to keep them simple.
– Jeroen
Dec 16 '12 at 21:39
You still haven't answered the question: what does doing the math gain you? Regardless of what you ultimately use (variables vs hard coded values)24px / 16px * 1em
has lower readability than1.5em
.
– cimmanon
Dec 16 '12 at 21:49
1
You have done a great disservice to Sass authors everywhere by reopening this question. It is now the top result on Google. Your "preferred method" is the worst possible way to append a unit to a number and only causes confusion when it doesn't work the way they expect down the road.
– cimmanon
Jun 26 '15 at 12:55
1
If you disagree with the most upvoted and accepted answer you should write a better answer, not rant in comments about it. - Explain why/when interpolation is the wrong tool of choice and/or tell folks one of the methods I mentioned already is the preferred way.
– Jeroen
Jun 30 '15 at 7:26
|
show 7 more comments
What does doing the math gain you (other than slower compilation and arguably lower readability)? Not every browser starts with a 16px font-size (historically, Opera used a smaller base font-size than other browsers... and users have been known to increase or decrease their font-size on purpose).
– cimmanon
Dec 16 '12 at 21:26
Once I replace the numbers with variables, the math will show meaning and/or intention, making it self-documenting instead of "magic". As I mention in the question, I left out variables in my examples to keep them simple.
– Jeroen
Dec 16 '12 at 21:39
You still haven't answered the question: what does doing the math gain you? Regardless of what you ultimately use (variables vs hard coded values)24px / 16px * 1em
has lower readability than1.5em
.
– cimmanon
Dec 16 '12 at 21:49
1
You have done a great disservice to Sass authors everywhere by reopening this question. It is now the top result on Google. Your "preferred method" is the worst possible way to append a unit to a number and only causes confusion when it doesn't work the way they expect down the road.
– cimmanon
Jun 26 '15 at 12:55
1
If you disagree with the most upvoted and accepted answer you should write a better answer, not rant in comments about it. - Explain why/when interpolation is the wrong tool of choice and/or tell folks one of the methods I mentioned already is the preferred way.
– Jeroen
Jun 30 '15 at 7:26
What does doing the math gain you (other than slower compilation and arguably lower readability)? Not every browser starts with a 16px font-size (historically, Opera used a smaller base font-size than other browsers... and users have been known to increase or decrease their font-size on purpose).
– cimmanon
Dec 16 '12 at 21:26
What does doing the math gain you (other than slower compilation and arguably lower readability)? Not every browser starts with a 16px font-size (historically, Opera used a smaller base font-size than other browsers... and users have been known to increase or decrease their font-size on purpose).
– cimmanon
Dec 16 '12 at 21:26
Once I replace the numbers with variables, the math will show meaning and/or intention, making it self-documenting instead of "magic". As I mention in the question, I left out variables in my examples to keep them simple.
– Jeroen
Dec 16 '12 at 21:39
Once I replace the numbers with variables, the math will show meaning and/or intention, making it self-documenting instead of "magic". As I mention in the question, I left out variables in my examples to keep them simple.
– Jeroen
Dec 16 '12 at 21:39
You still haven't answered the question: what does doing the math gain you? Regardless of what you ultimately use (variables vs hard coded values)
24px / 16px * 1em
has lower readability than 1.5em
.– cimmanon
Dec 16 '12 at 21:49
You still haven't answered the question: what does doing the math gain you? Regardless of what you ultimately use (variables vs hard coded values)
24px / 16px * 1em
has lower readability than 1.5em
.– cimmanon
Dec 16 '12 at 21:49
1
1
You have done a great disservice to Sass authors everywhere by reopening this question. It is now the top result on Google. Your "preferred method" is the worst possible way to append a unit to a number and only causes confusion when it doesn't work the way they expect down the road.
– cimmanon
Jun 26 '15 at 12:55
You have done a great disservice to Sass authors everywhere by reopening this question. It is now the top result on Google. Your "preferred method" is the worst possible way to append a unit to a number and only causes confusion when it doesn't work the way they expect down the road.
– cimmanon
Jun 26 '15 at 12:55
1
1
If you disagree with the most upvoted and accepted answer you should write a better answer, not rant in comments about it. - Explain why/when interpolation is the wrong tool of choice and/or tell folks one of the methods I mentioned already is the preferred way.
– Jeroen
Jun 30 '15 at 7:26
If you disagree with the most upvoted and accepted answer you should write a better answer, not rant in comments about it. - Explain why/when interpolation is the wrong tool of choice and/or tell folks one of the methods I mentioned already is the preferred way.
– Jeroen
Jun 30 '15 at 7:26
|
show 7 more comments
5 Answers
5
active
oldest
votes
up vote
54
down vote
accepted
The only way to add a unit to a number is via arithmetic.
To perform operations like concatenation (eg. 1 + px
) or interpolation (eg. #{1}px
) will only create a string that looks like a number. Even if you're absolutely 100% certain that you're never going to use your value in another arithmetic operation, you should not do this.
More important than not being able to perform arithmetic operations, you won't be able to use them with other functions that expects a number:
$foo: 1; // a number
$foo-percent: $foo + '%'; // a string
.bar {
color: darken(blue, $foo-percent); //Error: "1%" is not a number!
}
$amount: "1%" is not a number for `darken'
There is nothing to be gained by casting your numbers to strings. Always use arithmetic (multiplication by 1, or addition by 0) to add a unit:
$foo: 1; // a number
$foo-percent: $foo * 1%; // still a number! //or: $foo + 0%
.bar {
color: darken(blue, $foo-percent); //works!
}
Output:
.bar {
color: #0000fa;
}
Here's a mixin I wrote as part of my Flexbox mixin library that will choke if you pass in a string (for those not familiar with Flexbox, the original specification only allows integers for the box-flex
property. flex: auto
or flex: 30em
cannot be made compatible with the comparable box-flex
property, so the mixin doesn't bother trying)
@mixin flex($value: 0 1 auto, $wrap: $flex-wrap-required, $legacy: $flex-legacy-enabled) {
@if $legacy and unitless(nth($value, 1)) {
@include legacy-flex(nth($value, 1));
}
@include experimental(flex, $value, flex-support-common()...);
}
@mixin legacy-flex($value: 0) {
@include experimental(box-flex, $value, $box-support...);
}
2
Fun fact: Just seconds after finding your answer here (unit conversion) I googled if Sass had a switch construct and I landed here: github.com/sass/sass/issues/554#issuecomment-18304635 Figure the odds, good sir. :D And thanks!
– maryisdead
Dec 5 '16 at 1:34
1
For percent and a sass variable $var, I used: #{$var}#{"%"}.
– Tyler
May 17 '17 at 21:57
Maybe changing "The only way to add a unit to a number is via arithmetic." → "... is via multiplication." would be more clear. I tried addition everywhere before realizing that it was exactly what not to do...
– Atav32
Mar 27 at 20:45
1
@Atav32 actually the addition is also possible, if you have$foo: 1;
then you can use$foo-percent: $foo + 0%
to convert it to percent like as$foo * 1%
– S.Serpooshan
2 days ago
add a comment |
up vote
27
down vote
You can try either of these:
font-size: $size * 1px;
or
font-size: $size + unquote("px");
Where $size
is the result of your calculation.
2
The second method worked out for me very well. I found out thatunquote("px");
is the key here. If we don't applyunquote
, thepx
will be rendered within quotes and the browser will be unable to render the value correctly. Hence applyingunquote
is essential.
– Devner
Mar 15 '16 at 13:56
1
This is the right answer in my opinion.
– ric
Feb 20 '17 at 20:28
Note that font-size: $size + px; (without any quotation around the px) is also possible which is so simpler than the second method! see my answer below
– S.Serpooshan
2 days ago
add a comment |
up vote
14
down vote
Choose the method you prefer
$font: 24px;
$base: 16px;
No variables
.item1 { font-size: #{(24px / 16px)}em; }
Using only variables
.item2 { font-size: #{$font / $base}em; }
One variable
.item3 { font-size: #{$font / 16px}em; }
.item4 { font-size: #{24px / $base}em; }
Output for all of them
.item1 { font-size: 1.5em; }
.item2 { font-size: 1.5em; }
.item3 { font-size: 1.5em; }
.item4 { font-size: 1.5em; }
The method used is called interpolation #{}
Can this same approach be used with the percentage sign? SCSS seems to grumble...
– iamkeir
Sep 2 '13 at 16:31
8
For the percentage sign you have to use the interpolation method as well, so for example#{(24px / 16px)}#{"%"}
will output1.5%
– electric_g
Sep 8 '13 at 9:58
9
You should NEVER EVER EVER do this. Ever. Under any circumstance. This will always give you a string, meaning you will never be able to use the result in a later mathematical operation.
– cimmanon
Apr 19 '15 at 14:57
6
Sass lead designer here! @cimmanon is right; this isn't a robust or idiomatic way of converting units. Sass's units are part of its arithmetic, and working with the unit arithmetic will help produce better, more maintainable stylesheets.
– Natalie Weizenbaum
Jul 6 '15 at 20:07
For percentage you could alternatively use#{(24px / 16px)}unquote("%")
– dude
Aug 11 '16 at 9:30
|
show 1 more comment
up vote
6
down vote
I assume the reason you're asking this is because, in the surrounding context, 1 em = 16 px, and you want to use this relationship to convert the target font size from pixels to ems.
If so, the right thing to do is to multiply the font size with the scaling factor 1em / 16px, like this:
$h1-font-size: 24px;
$body-font-size: 16px;
$body-em-scale: 1em / $body-font-size;
h1 {
font-size: $h1-font-size * $body-em-scale; // -> 1.5em
}
or just:
h1 {
font-size: $h1-font-size * (1em / $body-font-size); // -> 1.5em
}
This is exactly how it works in physics, too: if have, say, 50 moles of water, and you want to know how much that weighs in grams, you multiply the amount of water you have (= 50 mol) with the molar mass of water (≈ 18 g/mol) to find out that your sample of water weighs 50 mol × 18 g/mol ≈ 900 grams. Converting pixels to ems in SASS works just the same way: first find out how many ems there are per pixel, in the context you intend to use the rule in, and then multiply the size in px with that ratio, expressed in units of em/px.
Ps. Of course, if the units you were converting between had a fixed ratio that SASS already knew about, then you could simply let it do the conversion automatically for you, using the "zero plus trick". For example, if you wanted to convert the font size from px to cm, you could simply do:
h1 {
font-size: 0cm + $h1-font-size; // -> 0.635cm
}
This works because SASS allows you to add together two values given in compatible units (like px and cm), and will express the result in the same units as the first value in the sum. The reason this trick doesn't work for px -> em is that here the conversion factor is not fixed, but depends on the surrounding context, and so SASS doesn't know how to do the conversion automatically.
So in other words, this question is a duplicate of an existing question? (see: stackoverflow.com/questions/15513395/…)
– cimmanon
Jun 26 '15 at 21:59
3
@cimmanon: Not exactly. That question asks how to append a unit to a unitless number. This one is asking how to convert a size measure between two different units (px -> em).
– Ilmari Karonen
Jun 26 '15 at 22:04
We already have a question about stripping units, too (see: stackoverflow.com/questions/12328259/…)
– cimmanon
Jun 26 '15 at 22:09
1
@cimmanon: The point I'm trying to make is that stripping and appending units willy-nilly is wrong here. The units are there for a reason, and you really should work with them, not just use hacks to strip them before doing math and then stick them back on again. And the proper way to convert between two units that don't have a fixed ratio is to find out the correct conversion ratio for your case and multiply by it.
– Ilmari Karonen
Jun 26 '15 at 22:18
add a comment |
up vote
0
down vote
The best way to add a unit, is to use ... * 1em
or ... + 0em
where em
is the unit you want to get:
font-size: (24px/16px) + 0em; // ... + 0px for px
//or
font-size: (24px/16px) * 1em;
//both produce: font-size: 1.5em;
This way, it will remain as a number you can use in other functions or math operations.
But if you want the result as a string or don't care the numeric value of result for some reason, you can also simply get it this way:
font-size: (24px/16px) + em; //font-size: 1.5em; //not em does not include quotations
no need to use unquote
or #{}
here (as written in other answers)!
add a comment |
5 Answers
5
active
oldest
votes
5 Answers
5
active
oldest
votes
active
oldest
votes
active
oldest
votes
up vote
54
down vote
accepted
The only way to add a unit to a number is via arithmetic.
To perform operations like concatenation (eg. 1 + px
) or interpolation (eg. #{1}px
) will only create a string that looks like a number. Even if you're absolutely 100% certain that you're never going to use your value in another arithmetic operation, you should not do this.
More important than not being able to perform arithmetic operations, you won't be able to use them with other functions that expects a number:
$foo: 1; // a number
$foo-percent: $foo + '%'; // a string
.bar {
color: darken(blue, $foo-percent); //Error: "1%" is not a number!
}
$amount: "1%" is not a number for `darken'
There is nothing to be gained by casting your numbers to strings. Always use arithmetic (multiplication by 1, or addition by 0) to add a unit:
$foo: 1; // a number
$foo-percent: $foo * 1%; // still a number! //or: $foo + 0%
.bar {
color: darken(blue, $foo-percent); //works!
}
Output:
.bar {
color: #0000fa;
}
Here's a mixin I wrote as part of my Flexbox mixin library that will choke if you pass in a string (for those not familiar with Flexbox, the original specification only allows integers for the box-flex
property. flex: auto
or flex: 30em
cannot be made compatible with the comparable box-flex
property, so the mixin doesn't bother trying)
@mixin flex($value: 0 1 auto, $wrap: $flex-wrap-required, $legacy: $flex-legacy-enabled) {
@if $legacy and unitless(nth($value, 1)) {
@include legacy-flex(nth($value, 1));
}
@include experimental(flex, $value, flex-support-common()...);
}
@mixin legacy-flex($value: 0) {
@include experimental(box-flex, $value, $box-support...);
}
2
Fun fact: Just seconds after finding your answer here (unit conversion) I googled if Sass had a switch construct and I landed here: github.com/sass/sass/issues/554#issuecomment-18304635 Figure the odds, good sir. :D And thanks!
– maryisdead
Dec 5 '16 at 1:34
1
For percent and a sass variable $var, I used: #{$var}#{"%"}.
– Tyler
May 17 '17 at 21:57
Maybe changing "The only way to add a unit to a number is via arithmetic." → "... is via multiplication." would be more clear. I tried addition everywhere before realizing that it was exactly what not to do...
– Atav32
Mar 27 at 20:45
1
@Atav32 actually the addition is also possible, if you have$foo: 1;
then you can use$foo-percent: $foo + 0%
to convert it to percent like as$foo * 1%
– S.Serpooshan
2 days ago
add a comment |
up vote
54
down vote
accepted
The only way to add a unit to a number is via arithmetic.
To perform operations like concatenation (eg. 1 + px
) or interpolation (eg. #{1}px
) will only create a string that looks like a number. Even if you're absolutely 100% certain that you're never going to use your value in another arithmetic operation, you should not do this.
More important than not being able to perform arithmetic operations, you won't be able to use them with other functions that expects a number:
$foo: 1; // a number
$foo-percent: $foo + '%'; // a string
.bar {
color: darken(blue, $foo-percent); //Error: "1%" is not a number!
}
$amount: "1%" is not a number for `darken'
There is nothing to be gained by casting your numbers to strings. Always use arithmetic (multiplication by 1, or addition by 0) to add a unit:
$foo: 1; // a number
$foo-percent: $foo * 1%; // still a number! //or: $foo + 0%
.bar {
color: darken(blue, $foo-percent); //works!
}
Output:
.bar {
color: #0000fa;
}
Here's a mixin I wrote as part of my Flexbox mixin library that will choke if you pass in a string (for those not familiar with Flexbox, the original specification only allows integers for the box-flex
property. flex: auto
or flex: 30em
cannot be made compatible with the comparable box-flex
property, so the mixin doesn't bother trying)
@mixin flex($value: 0 1 auto, $wrap: $flex-wrap-required, $legacy: $flex-legacy-enabled) {
@if $legacy and unitless(nth($value, 1)) {
@include legacy-flex(nth($value, 1));
}
@include experimental(flex, $value, flex-support-common()...);
}
@mixin legacy-flex($value: 0) {
@include experimental(box-flex, $value, $box-support...);
}
2
Fun fact: Just seconds after finding your answer here (unit conversion) I googled if Sass had a switch construct and I landed here: github.com/sass/sass/issues/554#issuecomment-18304635 Figure the odds, good sir. :D And thanks!
– maryisdead
Dec 5 '16 at 1:34
1
For percent and a sass variable $var, I used: #{$var}#{"%"}.
– Tyler
May 17 '17 at 21:57
Maybe changing "The only way to add a unit to a number is via arithmetic." → "... is via multiplication." would be more clear. I tried addition everywhere before realizing that it was exactly what not to do...
– Atav32
Mar 27 at 20:45
1
@Atav32 actually the addition is also possible, if you have$foo: 1;
then you can use$foo-percent: $foo + 0%
to convert it to percent like as$foo * 1%
– S.Serpooshan
2 days ago
add a comment |
up vote
54
down vote
accepted
up vote
54
down vote
accepted
The only way to add a unit to a number is via arithmetic.
To perform operations like concatenation (eg. 1 + px
) or interpolation (eg. #{1}px
) will only create a string that looks like a number. Even if you're absolutely 100% certain that you're never going to use your value in another arithmetic operation, you should not do this.
More important than not being able to perform arithmetic operations, you won't be able to use them with other functions that expects a number:
$foo: 1; // a number
$foo-percent: $foo + '%'; // a string
.bar {
color: darken(blue, $foo-percent); //Error: "1%" is not a number!
}
$amount: "1%" is not a number for `darken'
There is nothing to be gained by casting your numbers to strings. Always use arithmetic (multiplication by 1, or addition by 0) to add a unit:
$foo: 1; // a number
$foo-percent: $foo * 1%; // still a number! //or: $foo + 0%
.bar {
color: darken(blue, $foo-percent); //works!
}
Output:
.bar {
color: #0000fa;
}
Here's a mixin I wrote as part of my Flexbox mixin library that will choke if you pass in a string (for those not familiar with Flexbox, the original specification only allows integers for the box-flex
property. flex: auto
or flex: 30em
cannot be made compatible with the comparable box-flex
property, so the mixin doesn't bother trying)
@mixin flex($value: 0 1 auto, $wrap: $flex-wrap-required, $legacy: $flex-legacy-enabled) {
@if $legacy and unitless(nth($value, 1)) {
@include legacy-flex(nth($value, 1));
}
@include experimental(flex, $value, flex-support-common()...);
}
@mixin legacy-flex($value: 0) {
@include experimental(box-flex, $value, $box-support...);
}
The only way to add a unit to a number is via arithmetic.
To perform operations like concatenation (eg. 1 + px
) or interpolation (eg. #{1}px
) will only create a string that looks like a number. Even if you're absolutely 100% certain that you're never going to use your value in another arithmetic operation, you should not do this.
More important than not being able to perform arithmetic operations, you won't be able to use them with other functions that expects a number:
$foo: 1; // a number
$foo-percent: $foo + '%'; // a string
.bar {
color: darken(blue, $foo-percent); //Error: "1%" is not a number!
}
$amount: "1%" is not a number for `darken'
There is nothing to be gained by casting your numbers to strings. Always use arithmetic (multiplication by 1, or addition by 0) to add a unit:
$foo: 1; // a number
$foo-percent: $foo * 1%; // still a number! //or: $foo + 0%
.bar {
color: darken(blue, $foo-percent); //works!
}
Output:
.bar {
color: #0000fa;
}
Here's a mixin I wrote as part of my Flexbox mixin library that will choke if you pass in a string (for those not familiar with Flexbox, the original specification only allows integers for the box-flex
property. flex: auto
or flex: 30em
cannot be made compatible with the comparable box-flex
property, so the mixin doesn't bother trying)
@mixin flex($value: 0 1 auto, $wrap: $flex-wrap-required, $legacy: $flex-legacy-enabled) {
@if $legacy and unitless(nth($value, 1)) {
@include legacy-flex(nth($value, 1));
}
@include experimental(flex, $value, flex-support-common()...);
}
@mixin legacy-flex($value: 0) {
@include experimental(box-flex, $value, $box-support...);
}
edited 2 days ago
S.Serpooshan
3,87021537
3,87021537
answered Dec 16 '12 at 21:23
cimmanon
52.8k10119140
52.8k10119140
2
Fun fact: Just seconds after finding your answer here (unit conversion) I googled if Sass had a switch construct and I landed here: github.com/sass/sass/issues/554#issuecomment-18304635 Figure the odds, good sir. :D And thanks!
– maryisdead
Dec 5 '16 at 1:34
1
For percent and a sass variable $var, I used: #{$var}#{"%"}.
– Tyler
May 17 '17 at 21:57
Maybe changing "The only way to add a unit to a number is via arithmetic." → "... is via multiplication." would be more clear. I tried addition everywhere before realizing that it was exactly what not to do...
– Atav32
Mar 27 at 20:45
1
@Atav32 actually the addition is also possible, if you have$foo: 1;
then you can use$foo-percent: $foo + 0%
to convert it to percent like as$foo * 1%
– S.Serpooshan
2 days ago
add a comment |
2
Fun fact: Just seconds after finding your answer here (unit conversion) I googled if Sass had a switch construct and I landed here: github.com/sass/sass/issues/554#issuecomment-18304635 Figure the odds, good sir. :D And thanks!
– maryisdead
Dec 5 '16 at 1:34
1
For percent and a sass variable $var, I used: #{$var}#{"%"}.
– Tyler
May 17 '17 at 21:57
Maybe changing "The only way to add a unit to a number is via arithmetic." → "... is via multiplication." would be more clear. I tried addition everywhere before realizing that it was exactly what not to do...
– Atav32
Mar 27 at 20:45
1
@Atav32 actually the addition is also possible, if you have$foo: 1;
then you can use$foo-percent: $foo + 0%
to convert it to percent like as$foo * 1%
– S.Serpooshan
2 days ago
2
2
Fun fact: Just seconds after finding your answer here (unit conversion) I googled if Sass had a switch construct and I landed here: github.com/sass/sass/issues/554#issuecomment-18304635 Figure the odds, good sir. :D And thanks!
– maryisdead
Dec 5 '16 at 1:34
Fun fact: Just seconds after finding your answer here (unit conversion) I googled if Sass had a switch construct and I landed here: github.com/sass/sass/issues/554#issuecomment-18304635 Figure the odds, good sir. :D And thanks!
– maryisdead
Dec 5 '16 at 1:34
1
1
For percent and a sass variable $var, I used: #{$var}#{"%"}.
– Tyler
May 17 '17 at 21:57
For percent and a sass variable $var, I used: #{$var}#{"%"}.
– Tyler
May 17 '17 at 21:57
Maybe changing "The only way to add a unit to a number is via arithmetic." → "... is via multiplication." would be more clear. I tried addition everywhere before realizing that it was exactly what not to do...
– Atav32
Mar 27 at 20:45
Maybe changing "The only way to add a unit to a number is via arithmetic." → "... is via multiplication." would be more clear. I tried addition everywhere before realizing that it was exactly what not to do...
– Atav32
Mar 27 at 20:45
1
1
@Atav32 actually the addition is also possible, if you have
$foo: 1;
then you can use $foo-percent: $foo + 0%
to convert it to percent like as $foo * 1%
– S.Serpooshan
2 days ago
@Atav32 actually the addition is also possible, if you have
$foo: 1;
then you can use $foo-percent: $foo + 0%
to convert it to percent like as $foo * 1%
– S.Serpooshan
2 days ago
add a comment |
up vote
27
down vote
You can try either of these:
font-size: $size * 1px;
or
font-size: $size + unquote("px");
Where $size
is the result of your calculation.
2
The second method worked out for me very well. I found out thatunquote("px");
is the key here. If we don't applyunquote
, thepx
will be rendered within quotes and the browser will be unable to render the value correctly. Hence applyingunquote
is essential.
– Devner
Mar 15 '16 at 13:56
1
This is the right answer in my opinion.
– ric
Feb 20 '17 at 20:28
Note that font-size: $size + px; (without any quotation around the px) is also possible which is so simpler than the second method! see my answer below
– S.Serpooshan
2 days ago
add a comment |
up vote
27
down vote
You can try either of these:
font-size: $size * 1px;
or
font-size: $size + unquote("px");
Where $size
is the result of your calculation.
2
The second method worked out for me very well. I found out thatunquote("px");
is the key here. If we don't applyunquote
, thepx
will be rendered within quotes and the browser will be unable to render the value correctly. Hence applyingunquote
is essential.
– Devner
Mar 15 '16 at 13:56
1
This is the right answer in my opinion.
– ric
Feb 20 '17 at 20:28
Note that font-size: $size + px; (without any quotation around the px) is also possible which is so simpler than the second method! see my answer below
– S.Serpooshan
2 days ago
add a comment |
up vote
27
down vote
up vote
27
down vote
You can try either of these:
font-size: $size * 1px;
or
font-size: $size + unquote("px");
Where $size
is the result of your calculation.
You can try either of these:
font-size: $size * 1px;
or
font-size: $size + unquote("px");
Where $size
is the result of your calculation.
answered Aug 27 '15 at 11:24
Naoise Golden
6,57534157
6,57534157
2
The second method worked out for me very well. I found out thatunquote("px");
is the key here. If we don't applyunquote
, thepx
will be rendered within quotes and the browser will be unable to render the value correctly. Hence applyingunquote
is essential.
– Devner
Mar 15 '16 at 13:56
1
This is the right answer in my opinion.
– ric
Feb 20 '17 at 20:28
Note that font-size: $size + px; (without any quotation around the px) is also possible which is so simpler than the second method! see my answer below
– S.Serpooshan
2 days ago
add a comment |
2
The second method worked out for me very well. I found out thatunquote("px");
is the key here. If we don't applyunquote
, thepx
will be rendered within quotes and the browser will be unable to render the value correctly. Hence applyingunquote
is essential.
– Devner
Mar 15 '16 at 13:56
1
This is the right answer in my opinion.
– ric
Feb 20 '17 at 20:28
Note that font-size: $size + px; (without any quotation around the px) is also possible which is so simpler than the second method! see my answer below
– S.Serpooshan
2 days ago
2
2
The second method worked out for me very well. I found out that
unquote("px");
is the key here. If we don't apply unquote
, the px
will be rendered within quotes and the browser will be unable to render the value correctly. Hence applying unquote
is essential.– Devner
Mar 15 '16 at 13:56
The second method worked out for me very well. I found out that
unquote("px");
is the key here. If we don't apply unquote
, the px
will be rendered within quotes and the browser will be unable to render the value correctly. Hence applying unquote
is essential.– Devner
Mar 15 '16 at 13:56
1
1
This is the right answer in my opinion.
– ric
Feb 20 '17 at 20:28
This is the right answer in my opinion.
– ric
Feb 20 '17 at 20:28
Note that font-size: $size + px; (without any quotation around the px) is also possible which is so simpler than the second method! see my answer below
– S.Serpooshan
2 days ago
Note that font-size: $size + px; (without any quotation around the px) is also possible which is so simpler than the second method! see my answer below
– S.Serpooshan
2 days ago
add a comment |
up vote
14
down vote
Choose the method you prefer
$font: 24px;
$base: 16px;
No variables
.item1 { font-size: #{(24px / 16px)}em; }
Using only variables
.item2 { font-size: #{$font / $base}em; }
One variable
.item3 { font-size: #{$font / 16px}em; }
.item4 { font-size: #{24px / $base}em; }
Output for all of them
.item1 { font-size: 1.5em; }
.item2 { font-size: 1.5em; }
.item3 { font-size: 1.5em; }
.item4 { font-size: 1.5em; }
The method used is called interpolation #{}
Can this same approach be used with the percentage sign? SCSS seems to grumble...
– iamkeir
Sep 2 '13 at 16:31
8
For the percentage sign you have to use the interpolation method as well, so for example#{(24px / 16px)}#{"%"}
will output1.5%
– electric_g
Sep 8 '13 at 9:58
9
You should NEVER EVER EVER do this. Ever. Under any circumstance. This will always give you a string, meaning you will never be able to use the result in a later mathematical operation.
– cimmanon
Apr 19 '15 at 14:57
6
Sass lead designer here! @cimmanon is right; this isn't a robust or idiomatic way of converting units. Sass's units are part of its arithmetic, and working with the unit arithmetic will help produce better, more maintainable stylesheets.
– Natalie Weizenbaum
Jul 6 '15 at 20:07
For percentage you could alternatively use#{(24px / 16px)}unquote("%")
– dude
Aug 11 '16 at 9:30
|
show 1 more comment
up vote
14
down vote
Choose the method you prefer
$font: 24px;
$base: 16px;
No variables
.item1 { font-size: #{(24px / 16px)}em; }
Using only variables
.item2 { font-size: #{$font / $base}em; }
One variable
.item3 { font-size: #{$font / 16px}em; }
.item4 { font-size: #{24px / $base}em; }
Output for all of them
.item1 { font-size: 1.5em; }
.item2 { font-size: 1.5em; }
.item3 { font-size: 1.5em; }
.item4 { font-size: 1.5em; }
The method used is called interpolation #{}
Can this same approach be used with the percentage sign? SCSS seems to grumble...
– iamkeir
Sep 2 '13 at 16:31
8
For the percentage sign you have to use the interpolation method as well, so for example#{(24px / 16px)}#{"%"}
will output1.5%
– electric_g
Sep 8 '13 at 9:58
9
You should NEVER EVER EVER do this. Ever. Under any circumstance. This will always give you a string, meaning you will never be able to use the result in a later mathematical operation.
– cimmanon
Apr 19 '15 at 14:57
6
Sass lead designer here! @cimmanon is right; this isn't a robust or idiomatic way of converting units. Sass's units are part of its arithmetic, and working with the unit arithmetic will help produce better, more maintainable stylesheets.
– Natalie Weizenbaum
Jul 6 '15 at 20:07
For percentage you could alternatively use#{(24px / 16px)}unquote("%")
– dude
Aug 11 '16 at 9:30
|
show 1 more comment
up vote
14
down vote
up vote
14
down vote
Choose the method you prefer
$font: 24px;
$base: 16px;
No variables
.item1 { font-size: #{(24px / 16px)}em; }
Using only variables
.item2 { font-size: #{$font / $base}em; }
One variable
.item3 { font-size: #{$font / 16px}em; }
.item4 { font-size: #{24px / $base}em; }
Output for all of them
.item1 { font-size: 1.5em; }
.item2 { font-size: 1.5em; }
.item3 { font-size: 1.5em; }
.item4 { font-size: 1.5em; }
The method used is called interpolation #{}
Choose the method you prefer
$font: 24px;
$base: 16px;
No variables
.item1 { font-size: #{(24px / 16px)}em; }
Using only variables
.item2 { font-size: #{$font / $base}em; }
One variable
.item3 { font-size: #{$font / 16px}em; }
.item4 { font-size: #{24px / $base}em; }
Output for all of them
.item1 { font-size: 1.5em; }
.item2 { font-size: 1.5em; }
.item3 { font-size: 1.5em; }
.item4 { font-size: 1.5em; }
The method used is called interpolation #{}
edited Jun 26 '15 at 11:18
jazzpi
1,251917
1,251917
answered Dec 20 '12 at 16:44
electric_g
83166
83166
Can this same approach be used with the percentage sign? SCSS seems to grumble...
– iamkeir
Sep 2 '13 at 16:31
8
For the percentage sign you have to use the interpolation method as well, so for example#{(24px / 16px)}#{"%"}
will output1.5%
– electric_g
Sep 8 '13 at 9:58
9
You should NEVER EVER EVER do this. Ever. Under any circumstance. This will always give you a string, meaning you will never be able to use the result in a later mathematical operation.
– cimmanon
Apr 19 '15 at 14:57
6
Sass lead designer here! @cimmanon is right; this isn't a robust or idiomatic way of converting units. Sass's units are part of its arithmetic, and working with the unit arithmetic will help produce better, more maintainable stylesheets.
– Natalie Weizenbaum
Jul 6 '15 at 20:07
For percentage you could alternatively use#{(24px / 16px)}unquote("%")
– dude
Aug 11 '16 at 9:30
|
show 1 more comment
Can this same approach be used with the percentage sign? SCSS seems to grumble...
– iamkeir
Sep 2 '13 at 16:31
8
For the percentage sign you have to use the interpolation method as well, so for example#{(24px / 16px)}#{"%"}
will output1.5%
– electric_g
Sep 8 '13 at 9:58
9
You should NEVER EVER EVER do this. Ever. Under any circumstance. This will always give you a string, meaning you will never be able to use the result in a later mathematical operation.
– cimmanon
Apr 19 '15 at 14:57
6
Sass lead designer here! @cimmanon is right; this isn't a robust or idiomatic way of converting units. Sass's units are part of its arithmetic, and working with the unit arithmetic will help produce better, more maintainable stylesheets.
– Natalie Weizenbaum
Jul 6 '15 at 20:07
For percentage you could alternatively use#{(24px / 16px)}unquote("%")
– dude
Aug 11 '16 at 9:30
Can this same approach be used with the percentage sign? SCSS seems to grumble...
– iamkeir
Sep 2 '13 at 16:31
Can this same approach be used with the percentage sign? SCSS seems to grumble...
– iamkeir
Sep 2 '13 at 16:31
8
8
For the percentage sign you have to use the interpolation method as well, so for example
#{(24px / 16px)}#{"%"}
will output 1.5%
– electric_g
Sep 8 '13 at 9:58
For the percentage sign you have to use the interpolation method as well, so for example
#{(24px / 16px)}#{"%"}
will output 1.5%
– electric_g
Sep 8 '13 at 9:58
9
9
You should NEVER EVER EVER do this. Ever. Under any circumstance. This will always give you a string, meaning you will never be able to use the result in a later mathematical operation.
– cimmanon
Apr 19 '15 at 14:57
You should NEVER EVER EVER do this. Ever. Under any circumstance. This will always give you a string, meaning you will never be able to use the result in a later mathematical operation.
– cimmanon
Apr 19 '15 at 14:57
6
6
Sass lead designer here! @cimmanon is right; this isn't a robust or idiomatic way of converting units. Sass's units are part of its arithmetic, and working with the unit arithmetic will help produce better, more maintainable stylesheets.
– Natalie Weizenbaum
Jul 6 '15 at 20:07
Sass lead designer here! @cimmanon is right; this isn't a robust or idiomatic way of converting units. Sass's units are part of its arithmetic, and working with the unit arithmetic will help produce better, more maintainable stylesheets.
– Natalie Weizenbaum
Jul 6 '15 at 20:07
For percentage you could alternatively use
#{(24px / 16px)}unquote("%")
– dude
Aug 11 '16 at 9:30
For percentage you could alternatively use
#{(24px / 16px)}unquote("%")
– dude
Aug 11 '16 at 9:30
|
show 1 more comment
up vote
6
down vote
I assume the reason you're asking this is because, in the surrounding context, 1 em = 16 px, and you want to use this relationship to convert the target font size from pixels to ems.
If so, the right thing to do is to multiply the font size with the scaling factor 1em / 16px, like this:
$h1-font-size: 24px;
$body-font-size: 16px;
$body-em-scale: 1em / $body-font-size;
h1 {
font-size: $h1-font-size * $body-em-scale; // -> 1.5em
}
or just:
h1 {
font-size: $h1-font-size * (1em / $body-font-size); // -> 1.5em
}
This is exactly how it works in physics, too: if have, say, 50 moles of water, and you want to know how much that weighs in grams, you multiply the amount of water you have (= 50 mol) with the molar mass of water (≈ 18 g/mol) to find out that your sample of water weighs 50 mol × 18 g/mol ≈ 900 grams. Converting pixels to ems in SASS works just the same way: first find out how many ems there are per pixel, in the context you intend to use the rule in, and then multiply the size in px with that ratio, expressed in units of em/px.
Ps. Of course, if the units you were converting between had a fixed ratio that SASS already knew about, then you could simply let it do the conversion automatically for you, using the "zero plus trick". For example, if you wanted to convert the font size from px to cm, you could simply do:
h1 {
font-size: 0cm + $h1-font-size; // -> 0.635cm
}
This works because SASS allows you to add together two values given in compatible units (like px and cm), and will express the result in the same units as the first value in the sum. The reason this trick doesn't work for px -> em is that here the conversion factor is not fixed, but depends on the surrounding context, and so SASS doesn't know how to do the conversion automatically.
So in other words, this question is a duplicate of an existing question? (see: stackoverflow.com/questions/15513395/…)
– cimmanon
Jun 26 '15 at 21:59
3
@cimmanon: Not exactly. That question asks how to append a unit to a unitless number. This one is asking how to convert a size measure between two different units (px -> em).
– Ilmari Karonen
Jun 26 '15 at 22:04
We already have a question about stripping units, too (see: stackoverflow.com/questions/12328259/…)
– cimmanon
Jun 26 '15 at 22:09
1
@cimmanon: The point I'm trying to make is that stripping and appending units willy-nilly is wrong here. The units are there for a reason, and you really should work with them, not just use hacks to strip them before doing math and then stick them back on again. And the proper way to convert between two units that don't have a fixed ratio is to find out the correct conversion ratio for your case and multiply by it.
– Ilmari Karonen
Jun 26 '15 at 22:18
add a comment |
up vote
6
down vote
I assume the reason you're asking this is because, in the surrounding context, 1 em = 16 px, and you want to use this relationship to convert the target font size from pixels to ems.
If so, the right thing to do is to multiply the font size with the scaling factor 1em / 16px, like this:
$h1-font-size: 24px;
$body-font-size: 16px;
$body-em-scale: 1em / $body-font-size;
h1 {
font-size: $h1-font-size * $body-em-scale; // -> 1.5em
}
or just:
h1 {
font-size: $h1-font-size * (1em / $body-font-size); // -> 1.5em
}
This is exactly how it works in physics, too: if have, say, 50 moles of water, and you want to know how much that weighs in grams, you multiply the amount of water you have (= 50 mol) with the molar mass of water (≈ 18 g/mol) to find out that your sample of water weighs 50 mol × 18 g/mol ≈ 900 grams. Converting pixels to ems in SASS works just the same way: first find out how many ems there are per pixel, in the context you intend to use the rule in, and then multiply the size in px with that ratio, expressed in units of em/px.
Ps. Of course, if the units you were converting between had a fixed ratio that SASS already knew about, then you could simply let it do the conversion automatically for you, using the "zero plus trick". For example, if you wanted to convert the font size from px to cm, you could simply do:
h1 {
font-size: 0cm + $h1-font-size; // -> 0.635cm
}
This works because SASS allows you to add together two values given in compatible units (like px and cm), and will express the result in the same units as the first value in the sum. The reason this trick doesn't work for px -> em is that here the conversion factor is not fixed, but depends on the surrounding context, and so SASS doesn't know how to do the conversion automatically.
So in other words, this question is a duplicate of an existing question? (see: stackoverflow.com/questions/15513395/…)
– cimmanon
Jun 26 '15 at 21:59
3
@cimmanon: Not exactly. That question asks how to append a unit to a unitless number. This one is asking how to convert a size measure between two different units (px -> em).
– Ilmari Karonen
Jun 26 '15 at 22:04
We already have a question about stripping units, too (see: stackoverflow.com/questions/12328259/…)
– cimmanon
Jun 26 '15 at 22:09
1
@cimmanon: The point I'm trying to make is that stripping and appending units willy-nilly is wrong here. The units are there for a reason, and you really should work with them, not just use hacks to strip them before doing math and then stick them back on again. And the proper way to convert between two units that don't have a fixed ratio is to find out the correct conversion ratio for your case and multiply by it.
– Ilmari Karonen
Jun 26 '15 at 22:18
add a comment |
up vote
6
down vote
up vote
6
down vote
I assume the reason you're asking this is because, in the surrounding context, 1 em = 16 px, and you want to use this relationship to convert the target font size from pixels to ems.
If so, the right thing to do is to multiply the font size with the scaling factor 1em / 16px, like this:
$h1-font-size: 24px;
$body-font-size: 16px;
$body-em-scale: 1em / $body-font-size;
h1 {
font-size: $h1-font-size * $body-em-scale; // -> 1.5em
}
or just:
h1 {
font-size: $h1-font-size * (1em / $body-font-size); // -> 1.5em
}
This is exactly how it works in physics, too: if have, say, 50 moles of water, and you want to know how much that weighs in grams, you multiply the amount of water you have (= 50 mol) with the molar mass of water (≈ 18 g/mol) to find out that your sample of water weighs 50 mol × 18 g/mol ≈ 900 grams. Converting pixels to ems in SASS works just the same way: first find out how many ems there are per pixel, in the context you intend to use the rule in, and then multiply the size in px with that ratio, expressed in units of em/px.
Ps. Of course, if the units you were converting between had a fixed ratio that SASS already knew about, then you could simply let it do the conversion automatically for you, using the "zero plus trick". For example, if you wanted to convert the font size from px to cm, you could simply do:
h1 {
font-size: 0cm + $h1-font-size; // -> 0.635cm
}
This works because SASS allows you to add together two values given in compatible units (like px and cm), and will express the result in the same units as the first value in the sum. The reason this trick doesn't work for px -> em is that here the conversion factor is not fixed, but depends on the surrounding context, and so SASS doesn't know how to do the conversion automatically.
I assume the reason you're asking this is because, in the surrounding context, 1 em = 16 px, and you want to use this relationship to convert the target font size from pixels to ems.
If so, the right thing to do is to multiply the font size with the scaling factor 1em / 16px, like this:
$h1-font-size: 24px;
$body-font-size: 16px;
$body-em-scale: 1em / $body-font-size;
h1 {
font-size: $h1-font-size * $body-em-scale; // -> 1.5em
}
or just:
h1 {
font-size: $h1-font-size * (1em / $body-font-size); // -> 1.5em
}
This is exactly how it works in physics, too: if have, say, 50 moles of water, and you want to know how much that weighs in grams, you multiply the amount of water you have (= 50 mol) with the molar mass of water (≈ 18 g/mol) to find out that your sample of water weighs 50 mol × 18 g/mol ≈ 900 grams. Converting pixels to ems in SASS works just the same way: first find out how many ems there are per pixel, in the context you intend to use the rule in, and then multiply the size in px with that ratio, expressed in units of em/px.
Ps. Of course, if the units you were converting between had a fixed ratio that SASS already knew about, then you could simply let it do the conversion automatically for you, using the "zero plus trick". For example, if you wanted to convert the font size from px to cm, you could simply do:
h1 {
font-size: 0cm + $h1-font-size; // -> 0.635cm
}
This works because SASS allows you to add together two values given in compatible units (like px and cm), and will express the result in the same units as the first value in the sum. The reason this trick doesn't work for px -> em is that here the conversion factor is not fixed, but depends on the surrounding context, and so SASS doesn't know how to do the conversion automatically.
edited Jun 26 '15 at 22:13
answered Jun 26 '15 at 21:53
Ilmari Karonen
36.7k566124
36.7k566124
So in other words, this question is a duplicate of an existing question? (see: stackoverflow.com/questions/15513395/…)
– cimmanon
Jun 26 '15 at 21:59
3
@cimmanon: Not exactly. That question asks how to append a unit to a unitless number. This one is asking how to convert a size measure between two different units (px -> em).
– Ilmari Karonen
Jun 26 '15 at 22:04
We already have a question about stripping units, too (see: stackoverflow.com/questions/12328259/…)
– cimmanon
Jun 26 '15 at 22:09
1
@cimmanon: The point I'm trying to make is that stripping and appending units willy-nilly is wrong here. The units are there for a reason, and you really should work with them, not just use hacks to strip them before doing math and then stick them back on again. And the proper way to convert between two units that don't have a fixed ratio is to find out the correct conversion ratio for your case and multiply by it.
– Ilmari Karonen
Jun 26 '15 at 22:18
add a comment |
So in other words, this question is a duplicate of an existing question? (see: stackoverflow.com/questions/15513395/…)
– cimmanon
Jun 26 '15 at 21:59
3
@cimmanon: Not exactly. That question asks how to append a unit to a unitless number. This one is asking how to convert a size measure between two different units (px -> em).
– Ilmari Karonen
Jun 26 '15 at 22:04
We already have a question about stripping units, too (see: stackoverflow.com/questions/12328259/…)
– cimmanon
Jun 26 '15 at 22:09
1
@cimmanon: The point I'm trying to make is that stripping and appending units willy-nilly is wrong here. The units are there for a reason, and you really should work with them, not just use hacks to strip them before doing math and then stick them back on again. And the proper way to convert between two units that don't have a fixed ratio is to find out the correct conversion ratio for your case and multiply by it.
– Ilmari Karonen
Jun 26 '15 at 22:18
So in other words, this question is a duplicate of an existing question? (see: stackoverflow.com/questions/15513395/…)
– cimmanon
Jun 26 '15 at 21:59
So in other words, this question is a duplicate of an existing question? (see: stackoverflow.com/questions/15513395/…)
– cimmanon
Jun 26 '15 at 21:59
3
3
@cimmanon: Not exactly. That question asks how to append a unit to a unitless number. This one is asking how to convert a size measure between two different units (px -> em).
– Ilmari Karonen
Jun 26 '15 at 22:04
@cimmanon: Not exactly. That question asks how to append a unit to a unitless number. This one is asking how to convert a size measure between two different units (px -> em).
– Ilmari Karonen
Jun 26 '15 at 22:04
We already have a question about stripping units, too (see: stackoverflow.com/questions/12328259/…)
– cimmanon
Jun 26 '15 at 22:09
We already have a question about stripping units, too (see: stackoverflow.com/questions/12328259/…)
– cimmanon
Jun 26 '15 at 22:09
1
1
@cimmanon: The point I'm trying to make is that stripping and appending units willy-nilly is wrong here. The units are there for a reason, and you really should work with them, not just use hacks to strip them before doing math and then stick them back on again. And the proper way to convert between two units that don't have a fixed ratio is to find out the correct conversion ratio for your case and multiply by it.
– Ilmari Karonen
Jun 26 '15 at 22:18
@cimmanon: The point I'm trying to make is that stripping and appending units willy-nilly is wrong here. The units are there for a reason, and you really should work with them, not just use hacks to strip them before doing math and then stick them back on again. And the proper way to convert between two units that don't have a fixed ratio is to find out the correct conversion ratio for your case and multiply by it.
– Ilmari Karonen
Jun 26 '15 at 22:18
add a comment |
up vote
0
down vote
The best way to add a unit, is to use ... * 1em
or ... + 0em
where em
is the unit you want to get:
font-size: (24px/16px) + 0em; // ... + 0px for px
//or
font-size: (24px/16px) * 1em;
//both produce: font-size: 1.5em;
This way, it will remain as a number you can use in other functions or math operations.
But if you want the result as a string or don't care the numeric value of result for some reason, you can also simply get it this way:
font-size: (24px/16px) + em; //font-size: 1.5em; //not em does not include quotations
no need to use unquote
or #{}
here (as written in other answers)!
add a comment |
up vote
0
down vote
The best way to add a unit, is to use ... * 1em
or ... + 0em
where em
is the unit you want to get:
font-size: (24px/16px) + 0em; // ... + 0px for px
//or
font-size: (24px/16px) * 1em;
//both produce: font-size: 1.5em;
This way, it will remain as a number you can use in other functions or math operations.
But if you want the result as a string or don't care the numeric value of result for some reason, you can also simply get it this way:
font-size: (24px/16px) + em; //font-size: 1.5em; //not em does not include quotations
no need to use unquote
or #{}
here (as written in other answers)!
add a comment |
up vote
0
down vote
up vote
0
down vote
The best way to add a unit, is to use ... * 1em
or ... + 0em
where em
is the unit you want to get:
font-size: (24px/16px) + 0em; // ... + 0px for px
//or
font-size: (24px/16px) * 1em;
//both produce: font-size: 1.5em;
This way, it will remain as a number you can use in other functions or math operations.
But if you want the result as a string or don't care the numeric value of result for some reason, you can also simply get it this way:
font-size: (24px/16px) + em; //font-size: 1.5em; //not em does not include quotations
no need to use unquote
or #{}
here (as written in other answers)!
The best way to add a unit, is to use ... * 1em
or ... + 0em
where em
is the unit you want to get:
font-size: (24px/16px) + 0em; // ... + 0px for px
//or
font-size: (24px/16px) * 1em;
//both produce: font-size: 1.5em;
This way, it will remain as a number you can use in other functions or math operations.
But if you want the result as a string or don't care the numeric value of result for some reason, you can also simply get it this way:
font-size: (24px/16px) + em; //font-size: 1.5em; //not em does not include quotations
no need to use unquote
or #{}
here (as written in other answers)!
answered 2 days ago
S.Serpooshan
3,87021537
3,87021537
add a comment |
add a comment |
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f13905407%2fappend-unit-type-to-the-result-of-a-calculation%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
What does doing the math gain you (other than slower compilation and arguably lower readability)? Not every browser starts with a 16px font-size (historically, Opera used a smaller base font-size than other browsers... and users have been known to increase or decrease their font-size on purpose).
– cimmanon
Dec 16 '12 at 21:26
Once I replace the numbers with variables, the math will show meaning and/or intention, making it self-documenting instead of "magic". As I mention in the question, I left out variables in my examples to keep them simple.
– Jeroen
Dec 16 '12 at 21:39
You still haven't answered the question: what does doing the math gain you? Regardless of what you ultimately use (variables vs hard coded values)
24px / 16px * 1em
has lower readability than1.5em
.– cimmanon
Dec 16 '12 at 21:49
1
You have done a great disservice to Sass authors everywhere by reopening this question. It is now the top result on Google. Your "preferred method" is the worst possible way to append a unit to a number and only causes confusion when it doesn't work the way they expect down the road.
– cimmanon
Jun 26 '15 at 12:55
1
If you disagree with the most upvoted and accepted answer you should write a better answer, not rant in comments about it. - Explain why/when interpolation is the wrong tool of choice and/or tell folks one of the methods I mentioned already is the preferred way.
– Jeroen
Jun 30 '15 at 7:26