2017-03-01 62 views
2

我创建使用下面的代码,它封装父元素中的SVG图标的SVG图标组件的SVG图标孩子的身高:自动高度不坚持

HTML

<div class="icon-wrapper"> 
    <svg class="icon"> 
    <!-- 
    The "icon-search" symbol comes from a SVG sprite in the doc body. 
    See live demo below... 
    --> 
    <use xlink:href="#icon-search"></use> 
    </svg> 
</div> 

CSS

body { 
    font-size: 48px; 
    color: black; 
} 

.icon-wrapper { 
    background-color: lightgreen; 
} 

.icon { 
    width: 1em; 
    height: 1em; 

    stroke-width: 0; 
    stroke: currentColor; 
    fill: currentColor; 

    background-color: red; 
} 

即使包装div的高度设置为auto(它的初始值)它以某种方式在其底部添加了一些填充,因此比围绕的SVG高几个像素。绿色区域不应该存在:

Erroneous wrapper height

这是为什么?

这里有一个活生生的例子,你可以玩:https://jsbin.com/huyojeniwi/1/edit?html,css,output

回答

1

这是因为SVG图像是内嵌元件,并且浏览器从底部保存的SPase用于这种 “长” 符号 “P”, “Q”,“Y ”。

有几种方法可以解决此: 第一:

.icon { display: block; }

二:

.icon-wrapper { font-size: 0; } .icon { font-size: 48px; } 

.icon-wrapper { line-heigth: 1em; } .icon { vertical-align: top } 
+0

感谢为什么空间实际上是附加信息那里! – suamikim

+0

@disstruct这就叫*** kerning ***不*** *** spase ***,阅读更多关于行内框[在这里](https://www.w3.org/TR/CSS2/visuren.html#inline-盒) –

+0

@Ahishek Pandey谢谢。看起来有趣 – disstruct

1

这是发生,因为svg标签是inline-block元素,设置line-height:0;父元素将修复它。

inline框继承其块的父元素如font-sizeline-height等可继承属性,并创建空间/容限。

For more info

body { 
 
    font-size: 48px; 
 
    color: black; 
 
} 
 

 
.icon-wrapper { 
 
    background-color: lightgreen; 
 
    line-height: 0; 
 
} 
 

 
.icon { 
 
    width: 1em; 
 
    height: 1em; 
 
    stroke-width: 0; 
 
    stroke: currentColor; 
 
    fill: currentColor; 
 
    background-color: red; 
 
}
<!-- Inlined SVG sprite --> 
 
<svg style="position: absolute; width: 0; height: 0; overflow: hidden;" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> 
 
    <defs> 
 
     <symbol id="icon-search" viewBox="0 0 26 28"> 
 
     <title>search</title> 
 
     <path d="M18 13c0-3.859-3.141-7-7-7s-7 3.141-7 7 3.141 7 7 7 7-3.141 7-7zM26 26c0 1.094-0.906 2-2 2-0.531 0-1.047-0.219-1.406-0.594l-5.359-5.344c-1.828 1.266-4.016 1.937-6.234 1.937-6.078 0-11-4.922-11-11s4.922-11 11-11 11 4.922 11 11c0 2.219-0.672 4.406-1.937 6.234l5.359 5.359c0.359 0.359 0.578 0.875 0.578 1.406z"></path> 
 
     </symbol> 
 
    </defs> 
 
    </svg> 
 

 
<div class="icon-wrapper"> 
 
    <svg class="icon"> 
 
     <use xlink:href="#icon-search"></use> 
 
    </svg> 
 
</div>