Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to calculate rem properly in sass?

We are for the first time developing an app and the designer has prototyped the layout in retina modus, although this is not our goal for the next release, then now what we have to do, is to get the values provided by him and divide by 2.

For instance, we have a label to show a text and the label has the following scss:

        label {
            font-family: $font-family-medium;
            color: color($colors, slate);
            font-size: 2.25rem / 2;
            letter-spacing: 0.0625rem / 2;
            line-height: 3.25rem / 2;
            white-space: normal;
        }

That is the result:

enter image description here

That looks good, but depending where I apply the code chrome tells that the css property is not valid. Ok, then I add the function calc to the code above:

        label {
            font-family: $font-family-medium;
            color: color($colors, slate);
            font-size: calc(2.25rem / 2);
            letter-spacing: calc(0.0625rem / 2);
            line-height: calc(3.25rem / 2);
            white-space: normal;
        }

So chrome stops complaining, but that is the result:

enter image description here

The text in label gets wayyy smaller.

What is the difference between using calc and not using calc in sass?

I suppose I'm missing some important layout/design concept?

UPDATE:

I just realized that the first code ist for chrome always invalid:

enter image description here

That is one point that I figured out. So the calculation of retina modus dividing by 2 is not good I guess?

like image 947
DAG Avatar asked Oct 18 '25 20:10

DAG


2 Answers

Creating the function

@function calculateRem($size) {
  $remSize: $size / 16px;
  @return #{$remSize}rem;
}

Creating the mixin

Next we create a mixin that calls the function:

@mixin fontSize($size) {
  font-size: $size; //Fallback in px
  font-size: calculateRem($size);
}

Sass

h1 {
  @include fontSize(32px);
}

check this article

like image 183
Cem Arguvanlı Avatar answered Oct 20 '25 11:10

Cem Arguvanlı


The problem is you are not doing the division, you get in CSS for example the value 0.0625rem / 2 and this is not valid CSS, You have to put in parentheses to get the correct value:

SCSS

label {
  font-family: arial;
  color:red;
  font-size: (2.25rem / 2);
  letter-spacing: (0.0625rem / 2);
  line-height: (3.25rem / 2);
  white-space: normal;
}

OUTPUT CSS

label {
  font-family: arial;
  color: red;
  font-size: 1.125rem;
  letter-spacing: 0.03125rem;
  line-height: 1.625rem;
  white-space: normal;
}

When you are using calc() CSS can do the division by itself.