1

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?

2
  • what is parent? elements dont have a .css() method. are you talking about jquery Commented May 26, 2016 at 13:54
  • This is JQuery method... Commented May 26, 2016 at 13:58

2 Answers 2

3

You need a space after the minus letter :

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

Fiddle here

Sign up to request clarification or add additional context in comments.

1 Comment

1 character.... ONE CHARACTER! Thank you so much! will mark as answer as soon as Stack lets me!
1

The + and - operators must always be surrounded by whitespace. So you have to add an extra space here:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.