Html svg 元素上的虚假边距
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22337292/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spurious margin on svg element
提问by S?ren L?vborg
I have a very simple document (see also JSFiddle):
我有一个非常简单的文档(另见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.)
出于某种原因,svg
元素获得了 3px 或 4px 的底部边距(即,body
元素的高度为 1007px、1008px 甚至 1009px;svg
使用浏览器调试工具检查时,边距本身为 0。)
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.
如果我svg
用 a替换div
,伪边距就会消失。该行为在 Opera 12、Chrome 33、Firefox 26 和 Internet Explorer 11 中是一致的,所以我相信该行为是设计和标准兼容的,我只是不明白。
回答by Josh Crozier
This is a common issue with inline
elements. To solve this, simply add vertical-align:top
.
这是inline
元素的常见问题。要解决这个问题,只需添加vertical-align:top
.
#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.
值得注意的是,该vertical-align
属性的默认值为baseline
。这解释了默认行为。值,如top
,middle
和bottom
将正确对齐。
Alternatively, you could make the element block
level. (example)
或者,您可以使元素block
级别。(例子)
回答by Andrew Swift
I had a related problem where I had a div containing an SVG:
我有一个相关的问题,我有一个包含 SVG 的 div:
<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.
并且在 DIV 中的 SVG 上方和下方都有巨大的边距,即使在 DIV 中使用 vertical-align:top 和在 SVG 中使用 display:block 也是如此。
I had set "width:100%" for the SVG's to make them fill the page.
我已经为 SVG 设置了“宽度:100%”以使它们填满页面。
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.
解决方案是为 SVG 的. 它们已经显示在正确的高度,但是添加这个可以消除奇怪的边距。
I would love to know how and why this worked.
我很想知道这是如何以及为什么有效。
回答by Peter L
My document had a single svg element that resized with the window. I used CSS overflow:hiddento prevent scroll bars appearing. IE:
我的文档有一个随窗口调整大小的 svg 元素。我使用 CSS overflow:hidden来防止滚动条出现。IE:
body {
overflow: hidden;
}