Html canvas center inside div without stretching canvas

I have html like:

.image-detail { height: 100%; width: 100%; display: block; position: relative; } canvas { display: block; } .image-detail-canvas { -moz-user-select: none; -webkit-user-select: none; max-width: 100% !important; max-height: 100% !important; position: absolute !important; left: 50% !important; top: 50% !important; transform: translate(-50%, -50%) !important; } 
 <div class="image-detail"> <canvas class="image-detail-canvas" id="image-canvas"> </canvas> </div> 

He centers the canvas, but the canvas is stretched.

I do not want the canvas to be stretched.

I want it to be centered without stretching. If the canvas is horizontally and horizontally, then and so on.

+5
source share
2 answers

Remove Position: absolute; and translate

Add some width to the canvas and put margin: 0 auto; hope this helps.

 canvas { border: 1px solid; padding: 0; margin: auto; display: block; position: absolute; top: 0; bottom: 0; left: 0; right: 0; } .image-detail-canvas { -moz-user-select: none; -webkit-user-select: none; max-width: 100% !important; max-height: 100% !important; } 
 <div class="image-detail"> <canvas class="image-detail-canvas" id="image-canvas" width="100" height="100"> </canvas> </div> 

Check here: fooobar.com/questions/72281 / ...

+4
source

It is enough to change position to absolute , as well as add width / height definitions to all the parent elements (also html and body ):

 html, body { width: 100%; height: 100%; margin: 0; } .image-detail { height: 100%; width: 100%; display: block; position: relative; } canvas { border: 1px solid; display: block; } .image-detail-canvas { position: relative; max-width: 100%; max-height: 100%; left: 50%; top: 50%; transform: translate(-50%, -50%); } 
 <div class="image-detail"> <canvas class="image-detail-canvas" id="image-canvas" width="100" height="100"> </canvas> </div> 
0
source

All Articles