Canvas page covers page in Internet Explorer

I center my canvas with this code:

position:absolute; top:50%; left:50%; margin-top:-200px; /* Half of canvas height */ margin-left:-275px; /* Half of canvas width */ 

It works great in all browsers except IE9 and 10. In Internet Explorer, it spans the entire page. Can canvas centering be supported in IE?

+7
source share
1 answer

Centering with margin: 0 auto; using display: block; It works in almost all browsers - those that support <canvas> .

Real-time 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 vertical center response. 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 an explanation. First, we place the canvas with a 50% offset from the top and left using position: absolute , setting top and left to 50% . Then, since your canvas has a static size, we add a negative margin (which you should never do when the element is not absolute) for half the width and size (550x400 / 2 = 275x200): margin-left: -275px; margin-top: -200px; margin-left: -275px; margin-top: -200px; .

Now the canvas will be displayed in the center of the screen. If you do this inside another element and want to focus on it, try adding position: relative; to this element, so it will use it as borders instead of a body.

Here is an example: http://jsbin.com/ovoziv/6

+7
source

All Articles