Using the calc() function in inline styles in React

avatar
Borislav Hadzhiev

Last updated: Apr 7, 2024
2 min

banner

# Using the calc() function in inline styles in React

To use the calc() function in React:

  1. Set the style prop on the element
  2. Pass the result of calling calc() as the value for a CSS property.
  3. The call to calc() should be wrapped in a string.
App.js
const App = () => { const navbarHeight = '200px'; const footerHeight = '100px'; return ( <div style={{ minHeight: `calc(100vh - ${navbarHeight} - ${footerHeight})`, }} > <h2>Hello world</h2> <div style={{width: 'calc(100% - 600px)'}}> <h2>Some content here</h2> </div> </div> ); }; export default App;

react using calc function

The code for this article is available on GitHub

We set the style prop on the div in order to use inline styles.

The first example uses a template literal to interpolate variables in the call to the calc() function.

App.js
<div style={{ minHeight: `calc(100vh - ${navbarHeight} - ${footerHeight})`, }} > ... </div>

The expressions in the dollar sign curly braces ${} syntax will get replaced with the actual values of the navbarHeight and footerHeight variables.

Note that template literals are wrapped in backticks ``, not single quotes.

The second example uses the calc() function to calculate the width of an element.

App.js
<div style={{width: 'calc(100% - 600px)'}}> <h2>Some content here</h2> </div>
The code for this article is available on GitHub

Note that the minus (or plus) sign has to have spaces on both sides.

The call to the calc() function has to be wrapped in a string.

I've also written an article on how to use !important with inline styles in React.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.