Horizontal centering for the HTML5 canvas element

by Shareef Dabdoub.

Normally for a block-level element, centering it on the page can be achieved by the following CSS:

margin: 0px auto;

which, using the shorthand property, tells the browser to set no margin for the top and bottom, and to automatically calculate the left and right margins. The auto property has the nice effect of centering the element within the parent (in the basic case, the browser window).

Unfortunately, applying this directly to the style of the canvas element does not work to center it. The solution is to wrap the canvas element in a div with the auto margin property and set to the same width as the canvas element:

<div style="width: 200px; margin: auto;">
    <canvas style="width: 200px; height: 200px; margin: 0px auto; border: solid 1px; background-color: #AAA;"></canvas>

If you're worried about backwards compatibility (specifically IE5/Win) there is a workaround.

Follow me on GitHub.