Home > Software engineering >  Why do we need to use a calc function for a simple operation in CSS?
Why do we need to use a calc function for a simple operation in CSS?

Time:01-01

In the MDN web docs calc example, I see a demo example with width: calc(10px 100px) but I could instead simply use width: 110px.

So isn't calc(10px 100px) complicating the code for a simple operation? How does calc really help me?

CodePudding user response:

Using calc is as you said, useless for two values of the same unit type, unless they're used through variables, e.g.:

:root {
    --some-width: 50px;
}

.some-element {
    width: calc(var(--some-width)   100px);
}

Which would compute to 150px if --some-width is kept as 50px, however, --some-width can be changed to anything else, making the calc useful in this example - but useless in the provided example of calc(10px 100px).

They're useful for combing relative units, such as em or % with other values (of irrelevant type).

See https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Values_and_units for relative length units.

The example of calc(10px 100px) is as you said correctly, introducing more processing without any good reasoning, although not at a large scale.

  •  Tags:  
  • css
  • Related