I've created a SVG icon component which wraps SVG icons inside a parent element using the following code:
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;
}
Even though the height of the wrapping div is set to auto
(its initial value) it somehow adds some padding to its bottom and is therefore a few pixels taller than the surrounded SVG. The green area shouldn't be there:
Why is this?
Here's a live example you can play with: https://jsbin.com/huyojeniwi/1/edit?html,css,output
This is because svg image is inline element and the browser saves spase from bottom for such "long" symbols as "p", "q", "y".
There is several solutions to this: First:
.icon { display: block; }
Second:
.icon-wrapper { font-size: 0; } .icon { font-size: 48px; }
Third
.icon-wrapper { line-heigth: 1em; } .icon { vertical-align: top }
This is happening because svg
tag is inline-block
element, setting line-height:0;
to parent element will fix it.
Inline boxes inherit inheritable properties such as font-size
, line-height
etc from their block parent element , and creates space/margin.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With