Spurious margin on svg element

Søren Løvborg picture Søren Løvborg · Mar 11, 2014 · Viewed 27.7k times · Source

I have a very simple document (see also JSFiddle):

<style>
html, body, svg, div {
    margin: 0;
    padding: 0;
    border: 0;
}
</style>
<body>
<svg id="foo"
   xmlns="http://www.w3.org/2000/svg"
   version="1.1"
   style="width: 768px; height: 1004px;">
</svg>
</body>

For some reason, the svg element gets a 3px or 4px bottom margin (that is, the body element gets a height of 1007px, 1008px or even 1009px; the svg margin itself is 0 when inspected using the browser debug tools.)

If I replace the svg with a div, the spurious margin disappears. The behavior is consistent across Opera 12, Chrome 33, Firefox 26 and Internet Explorer 11, so I'm confident that the behavior is by design and standards compliant, I just don't get it.

Answer

Josh Crozier picture Josh Crozier · Mar 11, 2014

This is a common issue with inline elements. To solve this, simply add vertical-align:top.

UPDATED EXAMPLE HERE

#foo {
    background: #fff;
    vertical-align:top;
}

It's worth noting that the default value for the vertical-align property is baseline. This explains the default behavior. Values such as top, middle, and bottom will correct the alignment.

Alternatively, you could make the element block level. (example)