Ronalds Vilciņš


The CSS calc() function

The CSS calc() function allows you to specify lengths, sizes, and other numeric values using a combination of mathematical operators and predefined CSS units.

One of the main advantages of using calc() is that it allows you to make responsive designs that adapt to the size and dimensions of the user’s device. For example, you could use calc() to set the width of an element as a percentage of the viewport width, while also subtracting a fixed number of pixels to account for padding or margins.

Here’s an example of how you might use calc() in your stylesheets:

.my-element {
  width: calc(100% - 20px);
  height: calc(50% + 10px);
}

In this example, the width of .my-element is set to 100% of the viewport width, minus 20 pixels. The height is set to 50% of the viewport height, plus 10 pixels.

You can use a variety of mathematical operators in calc(), including addition (+), subtraction (-), multiplication (*), and division (/). You can also use parentheses to group calculations and specify the order of operations.

Here’s another example that uses multiple operators:

.my-other-element {
  width: calc((100% / 3) - 10px);
  height: calc(50% * 2);
}

In this example, the width of .my-other-element is set to one-third of the viewport width, minus 10 pixels. The height is set to double the height of the viewport.

It’s important to note that calc() is not supported in all browsers, so you may need to use vendor prefixes or fallback values to ensure compatibility with older browsers.

Overall, the CSS calc() function is a valuable tool for performing mathematical calculations within your stylesheets. It can help you create responsive designs that adapt to the size and dimensions of the user’s device, and it can save you time by allowing you to specify values using a combination of mathematical operators and CSS units.