Search code examples
javascripthtmlcssconcatenationcalc

Setting 'calc()' value by joining 2 strings in JavaScript not working


This is a bare bones example of the problem I have but the basic issue remains: The blue element needs to be styled as specified on the 3rd line in the JavaScript but fails to work. I have a few variables and strings to concatenate in the height value of this element. The red element is rendered correctly, but why does the blue element not work when I concatenate the values like this and how can I fix?

blue.style.height = 'calc( 100% -' + '2rem )';

This line is not working.

Note: I have to concatenate multiple variables and values within the calc value of an element. What can do I to get this to work while keeping the ability to string together multiple values?

var red = document.querySelector( '.red' ),
    green = document.querySelector( '.green' ),
    blue = document.querySelector( '.blue' );

red.style.height = 'calc( 100% - 2rem )';
blue.style.height = 'calc( 100% -' + '2rem )';
* {
  box-sizing: border-box;
  margin: 0;
}
html,
body {
  height: 100%;
}
body {
  display: flex;
  justify-content: space-around;
  padding: 1rem;
  background-color: #f8f8f8;
}
div {
  width: 5rem;
  height: 5rem;
}
.red {
  background-color: #e44;
}
.green {
  background-color: #4d4;
}
.blue {
  background-color: #0dd;
}
<div class="red"></div>
<div class="green"></div>
<div class="blue"></div>


Solution

  • Your concatenated string is missing the space, so -2rem is parsed as a negative value.

    blue.style.height = 'calc( 100% - ' + '2rem )';