Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

html

css

icons

svg

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:

Erroneous wrapper height

Why is this?

Here's a live example you can play with: https://jsbin.com/huyojeniwi/1/edit?html,css,output

like image 452
suamikim Avatar asked Mar 01 '17 11:03

suamikim


2 Answers

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 }
like image 170
disstruct Avatar answered Sep 28 '22 06:09

disstruct


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>
like image 20
Abhishek Pandey Avatar answered Sep 28 '22 06:09

Abhishek Pandey