简体   繁体   中英

Unexplained extra vertical space in SVG

I'm using inline SVGs on a site, but I'm having a problem with some of them being sized differently. Here's an example CodePen (code is below too). You can see that the first and second SVGs have the exact same height set and width is auto, so I would expect them to fill the height of the box and have their widths adjust to match. If you inspect the inner <path> element compared to the containing <svg> element, however, you'll see that the SVGs have some sort of padding around them, and that's why the sizes are different.

What is that extra padding and how can I get rid of it?

 div { height: 50px; width: 50px; border: 1px red solid; } svg { height: 100%; width: auto; }
 <div> <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"> <path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM8 9h8v10H8V9zm7.5-5l-1-1h-5l-1 1H5v2h14V4h-3.5z"></path> </svg> </div> <div> <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"> <path d="M16 1H4c-1.1 0-2.9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2.9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z"></path> </svg> </div>

That's normally how svg works. You can think of svg like canvas and container element <div> is its frame. <path> is like drawing on canvas and how you draw is specified by attribute called d , for example, M6 19 is moving to position at 6px (horizontal) and 19px (vertical).

svg path

Adjusting path by hand to fit svg(canvas) is quite hard. I suggest to adjust it by vector graphic tool like illustator or by adjusting viewBox of svg element (it's like moving/resize all drawing on canvas)

The SVG element is a kind of canvas where all the inner elements are absolutely positioned. You viewbox attribute is defining the size of the coordinate system within the svg.

Your path is therefore absolutely positioned in the viewbox coordinate system. If you want your path to fill the entire viewbox you need to modify the coordinate of the path itself.

If you were to simplify this example with a rectangle it will be:

// fill the entire viewbox
<svg viewbox="0 0 24 24">
  <rect x="0" y="0" width="24" height="24" />
</svg>

compare to the "padding" your are talking about:

// give 2px around the rectangle
<svg viewbox="0 0 24 24">
  <rect x="2" y="2" width="22" height="22" />
</svg>

For complex path like this one it is easier to manipulate them in an app like sketch or illustrator.

I hope my example helps you solve your problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM