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
Broxzier
source share