2

I have multiple canvases layered over eachother, basically I'm making a paint app that has history and delete. The canvases are not the same width as the parent div.

I was banging my head on the desk trying to center my canvas within the div until I read this answer, which is pretty much the lowest voted question.

In short:

The above answers only work if your canvas is the same width as the container.

This works regardless:

#container {
        margin: 0px auto;
        text-align: center;
}

If I comment out text-align my canvases go off center.

Q: How does this make any sense and why does text-align have an effect on canvas elements?

There are some weird quirks about CSS that I've learned in similar ways and use quite often. I think understanding this will be another tool in the chest to use.

gman
  • 100,619
  • 31
  • 269
  • 393
user409938289
  • 97
  • 1
  • 12

1 Answers1

1

canvas is a by default an inline element (just like img, input, etc.) so it is displayed inside the text flow. Run the example below to see an example.

Give the canvas display: block to make it a block element.

<p>This is a longer text with inline elements such as canvas <canvas style="width: 1em; height: 1em; border: 1px solid red;"></canvas>, image <img src="http://lorempixel.com/20/20/" /> and an <input type="button" value="input" /> element.</p>

<p>Give the canvas <code>display: block</code>, like this one <canvas style="width: 1em; height: 1em; border: 1px solid red; display: block"></canvas>, so that it becomes an block element.</p>
RoToRa
  • 37,635
  • 12
  • 69
  • 105