Using the calc() function in inline styles in React


Borislav Hadzhiev

Last updated: Apr 26, 2022


Check out my new book

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, e.g. 'calc(100% - 600px)'.
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 first example uses a template literal to interpolate variables in the call to the calc() function.

<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 we template literals are wrapped in backticks ``, not single quotes.

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

<div style={{width: 'calc(100% - 600px)'}}> <h2>Some content here</h2> </div>

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 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.