pixels-to-ems
view sourceConvert pixel-values to em
-values.
- use-name
-
scut-em
- type
- function, with an exposed settings-variable
- arguments
-
-
$pixels
-
$base
- default
-
16
A base-value with which to calculate the
em
-value. If there are no units, it's interpreted as pixels; but you can useem
-values, as well. The$base
default value can be changed for your project by setting your own$scut-em-base
variable prior to using this function (see examples).
-
Pass a single value or a list of values.
This function eases the burden on those who build flexible, em
-based layouts but still find themselves thinking in pixels or using tools that speak in pixels.
Unlike other px-to-ems mixins I've seen, this one provides flexibility for situations in which the em
-value has to be calculated in relation to something other than a default 16px font-size
.
If a $base
argument is provided, the em
-value will be calculated relative to that $base
(by default, $base
is assumed to be 16
). If that $base
is in pixels, everything should work smoothly, no questions asked. You can also provide a $base
in ems — but this is trickier: it will only work if your em
s are not more than one layer deep.
(For example, if your element is the child of a container whose font-size
is an em
-value other than 1em
, you can pass the font-size
as the $base
argument and everything will work fine (see example variations 5 and 6), But if the container has a font-size
in em
s (not 1em
), and a child of it has a font-size
in em
s (also not 1em
), and you're adjusting a grandchild ... things will probably go wrong. So, again, I don't suggest trying to use this function three or more levels deep in em
-relativity.)
If you're worried about these nesting issues and want to use rem
units, instead, try the scut-rem
function or the scut-rem-fallback
mixin.
example
SCSS
// first pair
.eg-em-1 { width: scut-em(150); }
.eg-em-2 { width: 150px; }
// second pair
.eg-em-3,
.eg-em-4 { font-size: 20px; }
.eg-em-3 { width: scut-em(250, 20); }
.eg-em-4 { width: 250px; }
// third pair
.eg-em-5,
.eg-em-6 { font-size: 0.6em; }
.eg-em-5 { width: scut-em(275, 0.6em); }
.eg-em-6 { width: 275px; }
// list and units demonstration
.eg-em-7 {
margin: scut-em(50 30px 0 60);
padding: scut-em(50 20px 0)
}
// changing the default $scut-em-base value
// (compare to the second pair, above)
$scut-em-base: 20;
.eg-em-8 {
font-size: 20px;
width: scut-em(250);
}
compiled CSS
.eg-em-1 {
width: 9.375em;
}
.eg-em-2 {
width: 150px;
}
.eg-em-3,
.eg-em-4 {
font-size: 20px;
}
.eg-em-3 {
width: 12.5em;
}
.eg-em-4 {
width: 250px;
}
.eg-em-5,
.eg-em-6 {
font-size: 0.6em;
}
.eg-em-5 {
width: 28.64583em;
}
.eg-em-6 {
width: 275px;
}
.eg-em-7 {
margin: 3.125em 1.875em 0em 3.75em;
padding: 3.125em 1.25em 0em;
}
.eg-em-8 {
font-size: 20px;
width: 12.5em;
}
The
px
-value you wish to convert toem
s. Nopx
unit necessary (e.g.20
is fine, so is20px
). Passing a list will result in a list ofem
values (see examples).