How do I center the canvas to the middle of the screen?

I have a canvas that automatically resizes, so it stretches from the top of the screen to the bottom of the screen while keeping a 1:1 Ratio. My problem is that I want to center it in the middle of the screen so that it looks nice. Ideally I want to use CSS and HTML to center it.

Repl link:

// Here is the code I've tried to center it.

<div style="text-align:center;">
  <canvas id="canvas"></canvas>

/* Unfortunately, this didn't center it correctly.
Furthermore, when the screen has more height than width, 
the canvas goes to the top left corner. */
element {
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);

Moves it to the center, and then puts the canvas center at that location.


That didn’t seem to work.

Yes, the white square is the canvas.
It’s so small… XD

I forgot the position: fixed; oopsie poopsie, add that to the canvas CSS

1 Like

Hey @ColoredHue, Welcome to the community!

You can check @NoNameByProgram‘s answer for centering elements. Just replace the <img> tag with your <canvas>.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.