2017-03-01 67 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>