bitshift
bitshift

Reputation: 6852

How to add rem to pixel value and store in variable?

In an scss file is it possible to do something like this?

$select-height: .75rem + 2px;

Upvotes: 5

Views: 5982

Answers (1)

Mark Little
Mark Little

Reputation: 345

There are 2 options I can come up with off the top of my head.

1: CSS calc() function

$select-height: calc(.75rem + 2px);

2: Convert px to rem

@function rem($px, $base: 16) {
  @return $px / $base;
};
$select-height: #{.75 + rem(2)}rem;

This assumes 16px is the basis for your rem units, which you can change by passing a second argument into your rem call. Stripping the units makes the math work. Alternatively, you can use a similar function to convert your rem to px by switching the division with multiplication. You could then convert the whole thing back to rem. But this is the simplest method I know of if you're doing rem-to-px math.

If you had a different variable for your base size in pixels, you could run a strip-units function like this:

@function strip-units($value) {
  @return $value / ($value * 0 + 1);
};

Upvotes: 11

Related Questions