How to center canvas in html5
I've been searching for a solution for a while now, but haven't found anything. Maybe it's just my search terms. Well, I'm trying to make the canvas center according to the size of the browser window. The canvas is 800x600. And if the window gets below 800x600, it should resize as well(but that's not very important at the moment)
Solution 1:
Give the canvas the following css style properties:
canvas {
padding-left: 0;
padding-right: 0;
margin-left: auto;
margin-right: auto;
display: block;
width: 800px;
}
Edit
Since this answer is quite popular, let me add a little bit more details.
The above properties will horizontally center the canvas, div or whatever other node you have relative to it's parent. There is no need to change the top or bottom margins and paddings. You specify a width and let the browser fill the remaining space with the auto margins.
However, if you want to type less, you could use whatever css shorthand properties you wish, such as
canvas {
padding: 0;
margin: auto;
display: block;
width: 800px;
}
Centering the canvas vertically requires a different approach however. You need to use absolute positioning, and specify both the width and the height. Then set the left, right, top and bottom properties to 0 and let the browser fill the remaining space with the auto margins.
canvas {
padding: 0;
margin: auto;
display: block;
width: 800px;
height: 600px;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
The canvas will center itself based on the first parent element that has position
set to relative
or absolute
, or the body if none is found.
Another approach would be to use display: flex
, that is available in IE11
Also, make sure you use a recent doctype such as xhtml or html 5.
Solution 2:
You can give your canvas the ff CSS properties:
#myCanvas
{
display: block;
margin: 0 auto;
}
Solution 3:
Just center the div in HTML:
#test {
width: 100px;
height:100px;
margin: 0px auto;
border: 1px solid red;
}
<div id="test">
<canvas width="100" height="100"></canvas>
</div>
Just change the height and width to whatever and you've got a centered div
http://jsfiddle.net/BVghc/2/