I'm centering my canvas using this code:
position:absolute;
top:50%;
left:50%;
margin-top:-200px; /* Half of canvas height */
margin-left:-275px; /* Half of canvas width */
It works perfect in all browsers except for IE9 and 10. In Internet Explorer, it covers the whole page. Is it possible to support the centering the canvas in IE?
Centring using margin: 0 auto;
with display: block;
works in almost all browser - the ones that support <canvas>
for sure.
Live example: http://jsbin.com/ovoziv/2
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Centring Canvas</title>
</head>
<body>
<canvas></canvas>
</body>
</html>
CSS
canvas {
display: block;
background: #FFFFB7;
width: 550px;
height: 400px;
margin: 0 auto;
}
EDIT: Updated answer to center vertically too. This CSS will do the trick:
canvas {
background-color: #FFFFB7;
width: 550px;
height: 400px;
position: absolute;
top: 50%;
left: 50%;
margin-left: -275px;
margin-top: -200px;
}
Now the explanation. We first place the canvas with 50% offset from the top and left-side using position: absolute
by setting top
and left
to 50%
. Then, because your canvas has a static size, we add a negative margin (which you should never do when the element is not absolute positioned) for half of the width and size (550x400/2 = 275x200): margin-left: -275px; margin-top: -200px;
.
The canvas will now be displayed at the center of the screen. If you do this inside another element and want to center in that one, try adding position: relative;
to that element, so it will use it's bounds instead of the body's.
Live example here: http://jsbin.com/ovoziv/6
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With