Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Why do we need to set the canvas' display to "block" when that is the default display setting anyway?

I am doing the "Create a Simple HTML5 Game" workshop, and in order to center the canvas element, we have to set the display to "block". At first, I thought that was redundant, because the canvas element is, by nature, a block element, but sure enough, the horizontal centering does not work unless the display is set to "block". Why is this???

body {
    background: #CE1138;}


canvas {
    display:block;
    margin:0 auto;
    background: #CCCCCC;
}

2 Answers

Hi Ryan,

I'm not really sure what to make of it. I found a few links saying canvas was a block level element. Also found some answers on stackoverflow which suggested that it was inline by default.

I put a canvas element on the page using codepen with firefox and I inspected the computed display property of it and it was inline. I also put a span right after it and they both appeared on the same line suggesting inline behavior.

Didn't personally test anymore browsers. Not sure if each browser sets what they want for that. Maybe it's a case of making sure your css reset or normalize.css is setting the display to either block or inline to make sure it will be the same across all browsers.

Hi Jason,

Thanks for doing that research for me. To me it certainly behaves like an inline element although sites claim it to be a block element. I guess, in the end, it doesn't matter too much. Thanks again.

I suppose that it is safer to explicitly set it to what you need for your project rather than hope that every browser has it set to either inline or block.

For instance, normalize.css has this:

/**
* 1. Correct `inline-block` display not defined in IE 8/9.
* 2. Normalize vertical alignment of `progress` in Chrome, Firefox, and Opera.
*/

audio,
canvas,
progress,
video {
  display: inline-block; /* 1 */
  vertical-align: baseline; /* 2 */
}

If you use normalize.css in your projects then you'll know that the canvas element will be consistently set as inline-block across all the browsers.