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.
This is done using the attribute "preserveAspectRatio" and setting it to "none". Hopefully this helps some of your understanding of SVGs, as they're a really useful tool!
Padding on an svg element actually widens the canvas upon which svg shapes can be visible. For instance, if you have an element that is on the edge of an SVG canvas, then you can add padding that will make that shape not cut off. Whereas margin will just affect the right/left positioning of the svg element.
The CSS margin properties are used to create space around elements, outside of any defined borders. With CSS, you have full control over the margins. There are properties for setting the margin for each side of an element (top, right, bottom, and left).
Any height or width you set for the SVG with CSS will override the height and width attributes on the <svg> . So a rule like svg {width: 100%; height: auto;} will cancel out the dimensions and aspect ratio you set in the code, and give you the default height for inline SVG.
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)
I had a related problem where I had a div containing an SVG:
<div id=contents> <svg exported from illustrator> </div>
and there were giant margins above and below the SVG in the DIV, even with vertical-align:top in the DIV and display:block in the SVG.
I had set "width:100%" for the SVG's to make them fill the page.
The solution was to set "height:100%" for the SVG's. They were already displaying at the correct height, but adding this got rid of the weird margins.
I would love to know how and why this worked.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With