Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

css
calc
styling
property values

How to use the calc() function in CSS

Educative Answers Team

In CSS, each element has certain properties which can be assigned by the user, based on individual needs. The calc() function provides a simpler approach to specifying the property values (eg. height, width etc.) by directly performing Mathematical calculations.

The calc() function supports the following fundamental Mathematical operations:

  1. Addition +
  2. Subtraction -
  3. Multiplication *
  4. Division \

One of the most distinctive features of the calc() function is that it supports operations on values with different units. This means that, for instance, you can add pixel values to percentages.

Syntax

Let’s take a look at the syntax of the calc() function:

svg viewer

The function takes as input a single mathematical expression, the result of which is set as the property value.

Note: For the addition + and subtraction - operators to function properly, they must be surrounded by whitespace, i.e. 80 + 10%.

The multiplication * and division / operators do not have any such requirements.

Example

Suppose you wish to set the width of two divs such that they are placed parallel to each other. Let’s see how we can accomplish this by using the subtraction - and division / operators:

  • HTML
  • CSS

As mentioned earlier, the addition + and subtraction - operators must be surrounded by whitespace to function properly.

Let’s see how removing the whitespace in the above code would change the output:

  • HTML
  • CSS

RELATED TAGS

css
calc
styling
property values
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring