Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Canvas covers page in Internet Explorer

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?

like image 581
user1431627 Avatar asked May 24 '13 09:05

user1431627


1 Answers

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

like image 113
Broxzier Avatar answered Sep 22 '22 17:09

Broxzier