Reputation: 3
$(document).ready(function(){
$("canvas").css({"border": "5px dotted white", "width": "600px", "height": "450px", "margin-left": "calc((window.innerWidth - 600px) / 2)"});
});
This is mainly a formatting issue I have. I know I'm doing it wrong, but I haven't been able to figure out what to do. In short, I'm trying to set a margin-left for a canvas that already exists, and the issue is the "margin-left": "calc((window.innerWidth - 600px) / 2)"
part. Every other part of this works perfectly fine when this part is not in it, but it instantly stops working when this code there, to which I assume it's just wrong.
How do I format this so the margin-left is set to the width of the window minus the width of the canvas(that's the 600px part), and then divided by half so it fits evenly in the middle of the screen. Is the formula formatted wrong? Is the attempt at coding it wrong? Or does .css just not like calc()?
Upvotes: 0
Views: 54
Reputation: 9459
You have to place Javascript's window.innerWidth
outside the quotes to let JS evaluate it as other said.
Or you can use CSS vw property like this:
"margin-left": "calc((100vw - 600px) / 2)"
Then you don't have to re-evaluate on window resize.
Upvotes: 1
Reputation: 943118
The CSS calc
property is not JavaScript. It does not have access to the DOM. You cannot use it with window.innerWidth
.
A calc-value can be any of these:
<calc-value> = <number> | <dimension> | <percentage> | ( <calc-sum> )
See also MDN.
Since you are setting the property with JS, you could calculate the side using JavaScript and generate the property value based on that. Note that you would probably want to bind a resize event so that you can update it if the window.innerWidth
changes.
Upvotes: 1