簡體   English   中英

div的自動高度不符合其SVG圖標子項的高度

[英]Auto height of div doesn't adhere to height of its SVG icon child

我創建了一個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高幾個像素。 綠色區域不應該在那里:

錯誤的包裝紙高度

為什么是這樣?

以下是您可以使用的實時示例: https//jsbin.com/huyojeniwi/1/edit?html,css,output

這是因為svg圖像是內聯元素,並且瀏覽器從“底部”為“p”,“q”,“y”這樣的“長”符號保存spase。

有幾種解決方案:第一:

.icon { display: block; }

第二:

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

第三

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

發生這種情況是因為svg標簽是inline-block元素,設置line-height:0; 到父元素將修復它。

內聯框從其塊父元素繼承可繼承的屬性,如font-sizeline-height等,並創建空格/邊距。

有關更多信息

 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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM