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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…