Steve B
Steve B

Reputation: 37660

How to preserve units with SASS computed variable?

I try to create some relative font-size values that match "nearly" pixels sizes:

html { font-size: 62.5%; }

$font-10px: 1em/1.1em;
$font-11px: 1.1em/1.1em;
$font-12px: 12em/11em;

.x10 { font-size: $font-10px; }
.x11 { font-size: $font-11px; }
.x12 { font-size: $font-12px; }

However, the output of this sass snipet is:

.x10 {
  font-size: 0.90909;
}

.x11 {
  font-size: 1;
}

.x12 {
  font-size: 1.09091;
}

As you can see, the unit (em) has been stripped.

This results in a incorrect value.

How should I declare my variables to contains the correct unit?

Upvotes: 0

Views: 211

Answers (2)

user3810867
user3810867

Reputation: 96

Add PX to the end of your variable and surround the variable with #{ }. This is known as interpolation #{ } and treats the variable as plain css. Interpolation also helps to remove any spaces between the number and unit of measurement:

$base-font-size: 16;
body  { font-size: (62.5% * base-font-size); }

$font-10px: 1em/1.1em;
$font-11px: 1.1em/1.1em;
$font-12px: 12em/11em;


.x10 { font-size: #{$font-10px}px; }
.x11 { font-size: #{$font-11px}px; }
.x12 { font-size: #{$font-12px}px; }

Result:

.x10 {
   font-size: 0.90909px;
}
.x11 {
   font-size: 1px;
}
.x12 {
   font-size: 1.09091px;
}

Since you mentioned accessability in the SA talk, I recommend that you add one of the mixins in this blog post by Hugo Giraudel to your project to allow the use REM units while also providing backwards compatibility for older browsers.

Upvotes: 0

cimmanon
cimmanon

Reputation: 68319

Dividing one length by another length always results in the unit being removed if the lengths are using the same units. So your options are:

  • Divide using one length and one integer: 1.1em / 1.1
  • Multiply the unit back on afterwards: 1.1em / 1.1em * 1em
  • Don't use division at all: 1em

Upvotes: 1

Related Questions