Search code examples
cssshorthandcss-calccss-variables

CSS variables with arithmetic operations don’t work in shorthand properties?


Please help me to find out why an arithmetic operation in CSS variable breaks the code.

I began with a simple CSS file with one rule:

html {
  font: 16px/32px Arial;
}

In browsers, it works as written: the font size is 16px, the line height is 32px, and the font itself is Arial.

Then I added the variables:

html {
  --default-font-size: 16px;
  --default-line-height: var(--default-font-size);
  font: var(--default-font-size)/var(--default-line-height) Arial;
}

It works, too; thought the line height is 16px, because I made it equal to the font size.

But when I multiplicated the second value, the font declaration stopped working:

html {
  --default-font-size: 16px;
  --default-line-height: var(--default-font-size) * 2;
  font: var(--default-font-size)/var(--default-line-height) Arial;  /* not working! */
}

All the properties font-size, line-height, and font-family are set to browser defaults.

If I split font shorthand property into three different longhand properties, the code works OK again:

html {
  --default-font-size: 16px;
  --default-line-height: var(--default-font-size) * 2;
  font-size: var(--default-font-size);
  line-height: var(--default-line-height);
  font-family: Arial;
}

What is wrong with the previous code sample and is there a way to make it work without splitting into longhand properties?


Solution

  • You need to use calc like this :

    html {
      --default-font-size: 16px;
      --default-line-height: calc(var(--default-font-size) * 2);
      font: var(--default-font-size)/var(--default-line-height) Arial;
    }
    

    The --default-line-height is replaced in the font property before getting evalutated so you have something like this (not valid) :

    font: var(--default-font-size)/var(--default-font-size) * 2 Arial;
    

    By the use of calc you evalute the expression and you have a valid syntax. Even your third example will not work. The CSS doesn't recognize the multiplication sign as it should be used inside a calc

    p {
      --default-font-size: 16px;
      --default-line-height: calc(var(--default-font-size) * 4);
      font: var(--default-font-size)/var(--default-line-height) Arial;
    }
    <p>lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum</p>