Can I use CSS calc within Javascript?

NickC picture NickC · Nov 29, 2016 · Viewed 36.5k times · Source

Can I use the css calc() function when setting positions in JavaScript?

ePopup.style.top = "calc(100px - 1.5em)";

Answer

Rounin picture Rounin · Nov 29, 2016

Yes, calc() will work when setting styles in javascript.

Working Example:

var innerDiv = document.getElementsByClassName('inner-div')[0];

function growInnerDiv() {
    innerDiv.style.setProperty('width', 'calc(100% + 224px)');
}

innerDiv.addEventListener('click', growInnerDiv, false);
.outer-div {
    display: inline-block;
    width: 200px;
    height: 100px;
    padding: 12px;
    border: 1px solid rgb(255,0,0);
    background-color: rgb(255,255,0);
}

.inner-div {
    width: 100px;
    height: 100px;
    color: rgb(255, 255, 255);
    font-weight: bold;
    text-align: center;
    line-height: 100px;
    font-family: arial, helvetica, sans-serif;
    background-color: rgb(255,0,0);
    cursor: pointer;
    transition: all 0.5s linear;
}
<div class="outer-div">
    <div class="inner-div">Click Me</div>
<div>