Html 如何摆脱div元素中svg下方的额外空间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24626908/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 02:13:00  来源:igfitidea点击:

How to get rid of extra space below svg in div element

htmlcsssvg

提问by Daniel

Here is an illustration of the problem (tested in Firefox and Chrome):

这是问题的说明(在 Firefox 和 Chrome 中测试):

<div style="background-color: red;"><svg height="100px" width="100" style="background-color: blue;"></svg></div>

View on JSFiddle

在 JSFiddle 上查看

Notice the extra redspace inside the divbelow the blue svg.

注意蓝色下方的额外red空间。divsvg

Already tried setting paddingand marginof both elements to 0, but with no luck.

已经尝试将paddingmargin两个元素都设置为0,但没有运气。

回答by Andy

You need display: block;on your svg.

你需要display: block;在你的svg.

<svg style="display: block;"></svg>

This is because inline-block elements (like <svg>and <img>) sit on the text baseline. The extra space you are seeing is the space left to accommodate character descenders (the tail on 'y', 'g' etc).

这是因为行内块元素(如<svg><img>)位于文​​本基线上。您看到的额外空间是用于容纳字符降序的空间('y'、'g' 等的尾部)。

You can also use vertical-align:topif you need to keep it inlineor inline-block

vertical-align:top如果需要保留inline或使用,您也可以使用inline-block

回答by Hiral

svgis an inlineelement. inlineelements leave white-space.

svg是一个inline元素。inline元素留下空白。

Solution:

解决方案:

Add display:blockto svg, or make height of parent div same as svg.

添加display:blocksvg,或使父 div 的高度与svg.

DEMO here.

演示在这里。

回答by ?ngelo Lucas

Another alternative is add font-size: 0to svg parent.

另一种选择是添加font-size: 0svg parent.

回答by Malachi

Change the displayproperty of the svg to be block.

display将 svg的属性更改为block.

回答by danrodi

Try adding height:100pxto divand using a height="100%"on svg:

尝试添加height:100pxdiv和使用height="100%"svg

<div style="background-color:red;height:100px">
    <svg height="100%" width="100" style="background-color:blue;"></svg>
</div>

回答by Farshad

simply add height to main div element

只需将高度添加到主 div 元素

<div style="background-color: red;height:100px"><svg height="100px" width="100" style="background-color: blue;"></svg></div>

回答by jcdsvg

Change your style to

改变你的风格

style="background-color: red; line-height: 0;"

样式=“背景颜色:红色;行高:0;”