Alex Wiley Alex Wiley - 1 year ago 161
jQuery Question

Using CSS property calc() with JS

I am needing to use the css calc() property to displace an element on the screen. Works fine if I do it via CSS however this CSS property need to be displaced by 50% - a variable worked out in JS.

See this example:

var displace = childHeight / 2
parent.css({'top': 'calc( 50% -' + displace + 'px)'});

When this runs however, it does not get applied to the HTML element on the page. To clarify that this DOES work with other stuff, if I were to type:

parent.css({'top': '50px'});

This would work and i've tested it and it applies. This means that there is an issue with applying the calc() via JS to a css element. Perhaps it is the way I have concatenated the variable into the calc().

Anybody have any suggestions?

Answer Source

You need a space after the minus letter :

var displace = childHeight / 2;
$(".test").css({'top': 'calc(50% - ' + displace + 'px)'});

Fiddle here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download