Ad space (banner)
🎨HTML & CSS Lessons
Lesson 49 / 50

Using a Calculated Value in CSS with calc()

In this lesson you'll learn how to specify a value using calculation with the calc() function, so you can build a layout combining values of different units. This is for people searching "CSS calc usage."

Using calc() lets you perform calculations inside CSS between values of different units, like "100% minus 40px." This is useful when building a responsive layout, like "the full width minus however much space is set aside for spacing."

The sample code places a fixed-width, 80px .sidebar on the left, and calculates .main's width as "the screen width minus the sidebar's share," with calc(100% - 100px). Confirm how the main area automatically adjusts to the right width even if you change the sidebar's width.

A common beginner stumbling block is that you always need a space on either side of an operator inside calc(). Writing it without spaces, like calc(100%-40px), results in an error and the calculation doesn't happen correctly. The rule is to always leave a space, as in calc(100% - 40px).

Units that normally can't simply be added or subtracted together, like percentages and pixels, can be calculated together inside calc(). This is commonly used for a layout combining a fixed-size sidebar with a flexible-size main area.

HTML & CSS
OUTPUT

💡 The preview runs entirely on this page — nothing is sent externally.

Ad space (banner)
Ad space (in-article)