Learn

Performing dynamic mathematical calculations to set property values might sound difficult, but the calc() function makes handling mathematical expressions simple. The calc() function takes a mathematical expression as its argument and returns the calculated value. We can use the calc() function as a value of CSS properties that expect numeric values.

The calc() function can be used to perform mathematical operations on a mix of units (rem, vw, px, etc). When performing addition (+) or subtraction (-), both numbers being operated on must have specified units. Division (/) requires the divisor (second operand) to be a unit-less number, and multiplication (*) requires one of the operands to be unit-less. Keep in mind that the calc() function requires whitespace between the operator and the numbers in the expression. The function can also be used as one of the multiple values for a property or argument in another function.

For example, what if we wanted to dynamically change the left and right margin of an element to be 1.5 percent of the viewport width added with 5px?

.item { margin: 15px calc(1.5vw + 5px); }

Above, we set the top and bottom margins of the .item selector to be 15px and use the calc() function to set the left and right margin values by adding 1.5vw and 5px. Notice the whitespace on either side of the +—it is required to add whitespace between operators and operands in the function.

A full list of operators, expression types, and use cases for calc() can be found on the Mozilla Developer Page.

Instructions

1.

The postcard title should scale depending on the size of the viewport. Inside the .card-title selector ruleset, replace the current font-size property value with the sum of 2vw and 1.5rem using the calc() function.

2.

The main card text should be centered no matter the size of the postcard. Inside the .card-text selector ruleset add a left property and set its value to be the difference of 50% and half of the width property’s value using the calc() function.

3.

Now, use the calc() function to set the margin on each item listed at the bottom of the postcard.

Navigate to the ul.activities selector ruleset and add a margin property. Set the first value of the property (for the top and bottom margin) to be the sum of 1vw and 0.5rem. The second property (for the left and right margin) value should be 2rem.

Take this course for free

By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.
Already have an account?