Can I use the css calc()
function when setting positions in JavaScript?
ePopup.style.top = \"calc(100px - 1.5em)\";
There are some interesting things that happen when you use calc
with the same type of units, e.g. 10px + 5px
. It gets simplified to 15px
by the process that puts it onto the element.
So, to expand on rounin's great answer, here's some examples of that behaviour in action:
function growDiv(e) {
const thisDiv = e.target;
const x = 100;
const y = 42;
const z = 69;
let widthVal;
if (thisDiv.id == "simplifies") {
widthVal = `calc(${y + z}px + ${x}px + ${y}px)`;
} else if (thisDiv.id == "mixed-units") {
widthVal = `calc(0em + ${y + z}px + ${x * 2}px + ${y}px)`;
} else if (thisDiv.id == "variables") {
thisDiv.style.setProperty("--x", x + "px");
thisDiv.style.setProperty("--y", y + "px");
thisDiv.style.setProperty("--z", z + "px");
widthVal = "calc((var(--x) * 2) + var(--y) + (var(--z) * 2))";
}
thisDiv.style.width = widthVal;
thisDiv.innerHTML =
`input: ${widthVal}
style:${thisDiv.style.width}`;
}
document
.querySelectorAll("div")
.forEach((el) => el.addEventListener("click", growDiv, false));
.inner-div {
background-color: hotpink;
color: white;
font-weight: bold;
height: 100px;
margin-bottom: 5px;
text-align: center;
transition: all 0.5s linear;
width: 100px;
}
simplifies
1) Click Me
mixed-units
2) Click Me
variables
3) Click Me
Div 1 has all the same units, and therefore simplifies.
Div 2 has a token 0em
unit, which makes no difference to the calculation, but forces the full expression to come through.
Div 3 is my favourite because it's a little bit self-documenting. I do this because I'm a bit forgetful and it lets me see why I set that element to 728.3 high, not just that I did.