How to center canvas in HTML and CSS?

Spread the love

Sometimes, we want to center canvas in HTML and CSS.

In this article, we’ll look at how to center canvas in HTML and CSS.

How to center canvas in HTML and CSS?

To center canvas in HTML and CSS, we use flexbox.

For instance, we write

<div class="canvas-container">
  <canvas width="150" height="200"></canvas>
</div>

to add a canvas inside a div.

Then we write

.canvas-container {
  display: flex;
  align-items: center;
  justify-content: center;
}

to make the div a flex container with display: flex;.

Then we vertically center the content of the div with align-items: center;.

And we vertically center the content of the div with justify-content: center;.

Conclusion

To center canvas in HTML and CSS, we use flexbox.

Leave a Reply

Your email address will not be published. Required fields are marked *