1

I'm trying to position an element by percentage but it didn't work out for me, it worked only when I used pixels.

Here is my code:

var x=document.getElementById("fir")
x.style.position = "absolute";
x.style.left = 10%
x.style.top = 10%

If I assigned to x.style.left any number followed by nothing it works fine but if I put percentage after the number like it's shown in the code above it doesn't work. Any ideas on how can I use the percentage to position this element?

3 Answers 3

9

Those values are supposed to be strings:

x.style.left = '10%';
x.style.top = '10%';

Otherwise, the % sign is interpreted as the remainder operator, leading to unexpected results or syntax errors (depending on your use of semicolons).

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

Comments

2

You'd have to assign it as a string. You're syntax is invalid, because 10% means something in JavaScript, so it's actually parsing x.style.left = 10%x.style.top = 10% since JS ignores whitespace.

Like bfavaretto said, you need to assign the values as strings:

x.style.left = '10%';
x.style.top = '10%';

and make sure you add your semicolons. :)

1 Comment

You're right, I missed that the first part is not a syntax error due to the missing semicolon. The last one still is, though.
1

The % is CSS syntax, not javascript syntax and you need to wrap it in quotes:

var x=document.getElementById("fir")
x.style.position = "absolute";
x.style.left = "10%";
x.style.top = "10%";

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.