27

I'm facing a strange problem.

in short :

When we put a canvas in a div and set the size of the canvas, the div is automatically 5px bigger than the canvas whereas I expect it to get the exact same size.

this question is a following of this answer so I'll take the same example, the issue has been reproduced in firefox and in google chrome. (didn't try other browsers)

<div>
    <canvas height="300px" width="200px"></canvas>
</div>

CSS :

div {
    border: 2px solid blue; /* demo purposes */
    display: inline-block;
}
canvas {
    background-color: khaki; /* demo purposes */
}

result (see the white space in the div) :

result

You can also see this exact same example (very simple) in this JSfiddle

Why does this happen and how can we prevent it ?

Community
  • 1
  • 1
Guian
  • 4,563
  • 4
  • 34
  • 54

1 Answers1

36

You can prevent it from happening by adding display: block to the css for the canvas element.

i.e:

canvas {
    background-color: khaki; /* demo purposes */
    display: block;
}
Matt Cain
  • 5,638
  • 3
  • 36
  • 45
  • 3
    thanks, but I'd like to know more about it, if I don't set the display to block, what is the default display value and why does it make an empty space under the canvas ? – Guian Apr 04 '13 at 12:10
  • 4
    The space appears due to the inline formatting model. It's a complicated subject that I don't fully understand myself but you can read up about it [here](http://reference.sitepoint.com/css/inlineformatting) and [here](http://meyerweb.com/eric/css/inline-format.html). – Matt Cain Apr 04 '13 at 12:36
  • 10
    +1, you're right of course! The space at the bottom is actual whitespace being rendered. If you [set the `line-height` to 0](http://jsfiddle.net/kpdgQ/) the space also disappears. – Jeroen Apr 08 '13 at 06:10
  • 2
    @Jeroen Which whitespace, if we have `
    `?
    – Rodrigo Apr 21 '21 at 07:21
  • Interesting! So I was wrong in 2013 I guess, or not precise enough, as it seems a line of text gets inserted even if the tags follow eachother directly. It _is_ a line of text I think though, if you go `* { font-size: 100px; }` the white space does grow. - Not sure what precisely is going on. – Jeroen Apr 21 '21 at 08:14