Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why do we need to use a calc function for a simple operation in CSS?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading