Wrap your canvas
element inside a div
and assign display: table-cell;
and than use vertical-align: middle;
as well as text-align: center;
to align vertically as well as horizontally
div {
display: table-cell;
height: 300px;
width: 300px;
vertical-align: middle;
text-align: center;
border: 1px solid #eee;
}
canvas {
height: 30px;
width: 30px;
border: 4px solid #f00;
}
Don't want to use display: table-cell;
? Than you can also achieve this using CSS Positioning. Here, am assigning position: relative;
to the container element, and than am making the child element position: absolute;
, just make sure you use margin: auto;
there as it's crucial.
div {
position: relative;
height: 300px;
width: 300px;
border: 1px solid #eee;
}
canvas {
height: 30px;
width: 30px;
border: 4px solid #f00;
position: absolute;
top: 0;
left: 0;
right: 0;
margin: auto;
bottom: 0;
}
Note: Am aware that the
height
andwidth
of thecanvas
are dynamic, but I am just using fixed for demonstration purposes.