Calculations using calc()
What is the calc() Function?
Imagine you are tailoring a coat. You want the sleeve length to cover the entire arm length (100%), minus exactly 5 centimeters at the wrist so the user can easily see their watch. You can't calculate this beforehand because you don't know the arm length of the customer. You must write a rule:Sleeve = Arm Length - 5cm.In CSS, the calc() function performs mathematical calculations directly inside your style values, dynamically combining different unit types:
width: calc(100% - 50px); โ Stretches the element to fill the full container width, minus exactly 50 pixels of space.Why does it matter?
calc() is incredibly useful for responsive layouts. For example, if you build a sidebar layout, you can set a sidebar to a fixed width of 250px, and make the main content container occupy the remaining width using width: calc(100% - 250px);, ensuring they fit side-by-side perfectly on any screen width.
Syntax Breakdown
width: calc(100% - 50px); โ Sets width dynamically.calc() function! Writing calc(100%-50px) without spaces is invalid and will be ignored by the browser.*Common Mistakes
- and addition + operators must have spaces on both sides. Otherwise, the browser reads -50px as a negative number rather than a subtraction operation, breaking the calculation!Quick Reference
calc(expression) โ Computes mathematical values for properties.Spaces required โ Math signs (+, -) require surrounding space.Your Task
Set the `width` property on the `.sidebar` class using `calc(100% - 50px)`.
index.html
Type code above to start the lesson.
Live Preview