Borislav Hadzhiev
Last updated: Apr 26, 2022
Check out my new book
To use the calc()
function in React:
style
prop on the elementcalc()
as the value for a CSS property.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;
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.